/// <summary> /// calculate distance from one state to another state /// </summary> /// <param name="state"></param> /// <returns></returns> public int GetDistance(State state) { var result = 9; for (int row = 0; row < 3; row++) { for (int col = 0; col < 3; col++) { if (this.Cells[row, col] == state.Cells[row, col]) result--; } } return result; }
static void Main(string[] args) { var target = new int[,] { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 0 } }; var origin = new int[,] { { 1, 3, 6 }, { 4, 2, 0 }, { 7, 5, 8 } }; var targetState = new State(target); var originState = new State(origin); INode<State> pOrigin = new PuzzleNode(targetState, originState); INode<State> pTarget = new PuzzleNode(targetState, targetState); Solver<State> solver = new Solver<State>(pOrigin, pTarget); var result = solver.Solve(); do { Console.WriteLine(result.Content.ToDisplayString() + Environment.NewLine); result = result.Parent; } while (result != null); Console.Read(); }
/// <summary> /// clone a new state from the current state /// </summary> /// <returns></returns> private State Clone() { var result = new State(new int[3,3]); for (int row = 0; row < 3; row++) { for (int col = 0; col < 3; col++) { result.Cells[row, col] = Cells[row, col]; } } return result; }