Skip to content

Instantly share code, notes, and snippets.

@notyy
Created May 4, 2012 15:26
Show Gist options
  • Select an option

  • Save notyy/2595509 to your computer and use it in GitHub Desktop.

Select an option

Save notyy/2595509 to your computer and use it in GitHub Desktop.
骑士问题
问题描述,有一个横8纵8的国际象棋棋盘,也就是坐标x,y都在(1..8)的范围内。
在棋盘的任意坐标上放一个马,马的走步规则,跟中国象棋差不多。。。如果不了解的话请谷歌之
现在给定棋盘上任意坐标,问这个马是否有可能精确的在第3步上走到该坐标?
=======================下面的解法译自haskell==================================
def moveKnight: (Int,Int) => List[(Int,Int)] = (c,r) => {
List((c+2,r-1),(c+2,r+1),(c-2,r-1),(c-2,r+1),
(c+1,r-2),(c+1,r+2),(c-1,r-2),(c-1,r+2)) filter (pos => (1 to 8).contains(pos._1) && (1 to 8).contains(pos._2))
}
val moveKnightT = moveKnight.tupled
def in3: (Int,Int) => List[(Int,Int)] = (x,y) => {
List((x,y)) flatMap moveKnightT flatMap moveKnightT flatMap moveKnightT
}
def canReachIn3: (Int,Int) => (Int,Int) => Boolean = (startX,startY) => (endX,endY) => {
in3(startX, startY) contains (endX,endY)
}
===================test case ============================
scala> canReachIn3(6,2)(6,1)
res0: Boolean = true
scala> canReachIn3(6,2)(7,3)
res1: Boolean = false
@sjbwylbs
Copy link

sjbwylbs commented May 5, 2012

good

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment