public static float GetManhattanDistance(SlidingTilesPuzzle.State state) { Cell[] coords; if (!_cache.TryGetValue(state.Size * state.Size, out coords)) { coords = new Cell[state.Size * state.Size]; for (var i = 0; i < state.Size * state.Size; i++) { coords[i] = new Cell { Row = (int)(i / (state.Size)), Col = i % (state.Size) }; } _cache.Add(state.Size * state.Size, coords); } var result = 0; for (var i = 0; i < state.Size * state.Size; i++) { if (i == state.Blank) continue; var v1 = coords[state.Tiles[i]].Row - coords[i].Row; var v2 = coords[state.Tiles[i]].Col - coords[i].Col; result += (v1 < 0 ? -v1 : v1) + (v2 < 0 ? -v2 : v2); } return result; }
private void RecreatePuzzle() { Text = "Size: " + trackBar1.Value + ", moves: " + trackBar2.Value; _problem = new Problems.SlidingTilesPuzzle(trackBar1.Value); _currentState = _problem.CreateJumbledState(trackBar2.Value); panel1.Invalidate(); }