| 11 | import java.util.Arrays; |
| 12 | |
| 13 | public class Board { |
| 14 | private static final int[][] DIR = { { 0, 1 }, { 0, -1 }, { 1, 0 }, { -1, 0 } }; |
| 15 | private final int n; |
| 16 | private final int[][] tiles; |
| 17 | private final int hammingD; |
| 18 | private final int manhattanD; |
| 19 | private final int emptyPosX; |
| 20 | private final int emptyPosY; |
| 21 | |
| 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() { |
| 54 | StringBuilder s = new StringBuilder(); |
| 55 | s.append(n + "\n"); |
| 56 | for (int i = 0; i < n; i++) { |
| 57 | for (int j = 0; j < n; j++) { |
| 58 | s.append(String.format("%2d ", tiles[i][j])); |
| 59 | } |
| 60 | s.append("\n"); |
| 61 | } |
| 62 | return s.toString(); |
| 63 | } |
| 64 | |
| 65 | // board dimension n |
| 66 | public int dimension() { |
| 67 | return n; |
| 68 | } |
| 69 | |
| 70 | // number of tiles out of place |
nothing calls this directly
no outgoing calls
no test coverage detected