有一个无限大的棋盘,棋盘上有一匹马,马移动的方式为日字型。即假设马当前的位置为(x,y),那么下一步可以移动到(x+1,y+2),(x+1,y-2),(x-1,y+2),(x-1,y-2),(x+2,y+1),(x+2,y-1),(x-2,y+1)或者(x-2,y-1)这8个位置。
问马是否能从坐标(x,y)按照上述移动规则移动到坐标(x2,y2)。
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication9 { class Program { static void Main(string[] args) { Coordinate a = new Coordinate(4, 4); Coordinate b = new Coordinate(6, 6); Console.Write(IsAbleMoveTo(a, b)); } static Coordinate MoveUpOne(Coordinate a) { a.x += 2; a.y += 1; a.x -= 1; a.y -= 2; a.x -= 1; a.y += 2; return a; } static Coordinate MoveDownOne(Coordinate a) { a.x += 1; a.y -= 2; a.x += 1; a.y += 2; a.x -= 2; a.x -= 1; return a; } static Coordinate MoveLeftOne(Coordinate a) { a.x -= 1; a.y += 2; a.x += 2; a.y -= 1; a.x -= 2; a.y -= 1; return a; } static Coordinate MoveRightOne(Coordinate a) { a.x += 2; a.y += 1; a.x -= 2; a.y += 1; a.x += 1; a.y -= 2; return a; } static bool IsAbleMoveTo(Coordinate a, Coordinate b) { int x = b.x - a.x; int y = b.y - a.y; if (x>0) { for (int i = 0; i < x; i++) { a=MoveRightOne(a); } } else { for (int i = 0; i < -x; i++) { a=MoveLeftOne(a); } } if (y>0) { for (int i = 0; i < y; i++) { a=MoveUpOne(a); } } else { for (int i = 0; i < -y; i++) { a=MoveDownOne(a); } } if (a.x == b.x && a.y == b.y) { return true; } else { return false; } } } struct Coordinate { public int x; public int y; public Coordinate(int a, int b) { x = a; y = b; } } }