MCPcopy Create free account
hub / github.com/MolinDeng/Princeton-algs4 / Board

Method Board

04Lab-8Puzzle/Board.java:24–50  ·  view source on GitHub ↗
(int[][] tiles)

Source from the content-addressed store, hash-verified

22 // create a board from an n-by-n array of tiles,
23 // where tiles[row][col] = tile at (row, col)
24 public Board(int[][] tiles) {
25 if (tiles == null) throw new IllegalArgumentException();
26 this.tiles = new int[tiles.length][tiles[0].length];
27 for (int i = 0; i < tiles.length; i++)
28 this.tiles[i] = Arrays.copyOf(tiles[i], tiles.length);
29 n = tiles.length;
30 // calculate hamming distance and manhattan distance
31 int h = 0, m = 0, px = 0, py = 0;
32 for (int i = 0; i < n; i++) {
33 for (int j = 0; j < n; j++) {
34 if (tiles[i][j] == 0) {
35 px = i;
36 py = j;
37 continue;
38 }
39 // if the tile is in the right position i * n + j + 1 = val
40 int val = tiles[i][j] - 1;
41 int man = Math.abs(val / n - i) + Math.abs(val % n - j);
42 if (man > 0) h++;
43 m += man;
44 }
45 }
46 manhattanD = m;
47 hammingD = h;
48 emptyPosX = px;
49 emptyPosY = py;
50 }
51
52 // string representation of this board
53 public String toString() {

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected