11import edu .princeton .cs .algs4 .StdOut ;
22
33public class Board {
4- int [][] tiles ;
4+ private int n ;
5+ public int [][] tiles ;
56
67 // create a board from an n-by-n array of tiles,
78 // where tiles[row][col] = tile at (row, col)
89 public Board (int [][] tiles ) {
910 this .tiles = tiles ;
11+ this .n = tiles .length ;
12+
13+ // this.goal = new int[n][n];
14+ // for(int z = 0; z < n * n - 1; ++z) {
15+ // goal[z / n][z % n] = z + 1;
16+ // }
1017 }
1118
1219 // string representation of this board
@@ -27,27 +34,66 @@ public String toString() {
2734
2835 // board dimension n
2936 public int dimension () {
30- return tiles . length ;
37+ return n ;
3138 }
3239
3340 // number of tiles out of place
3441 public int hamming () {
35- return 0 ;
42+ int cnt = 0 ;
43+ for (int i = 0 ; i < dimension (); ++i ) {
44+ for (int j = 0 ; j < dimension (); ++j ) {
45+ if (tiles [i ][j ] != goalAt (i , j )) {
46+ cnt ++;
47+ }
48+ } }
49+ return cnt ;
3650 }
3751
3852 // sum of Manhattan distances between tiles and goal
3953 public int manhattan () {
40- return 0 ;
54+ int cnt = 0 ;
55+ for (int i = 0 ; i < dimension (); ++i ) {
56+ for (int j = 0 ; j < dimension (); ++j ) {
57+ int v = tiles [i ][j ];
58+ v = v == 0 ? n * n : v ;
59+ int x = (v - 1 ) / n ;
60+ int y = (v - 1 ) % n ;
61+
62+ int xd = Math .abs (x - j );
63+ int xy = Math .abs (y - i );
64+
65+ cnt += xd + xy ;
66+ } }
67+ return cnt ;
4168 }
4269
4370 // is this board the goal board?
4471 public boolean isGoal () {
45- return false ;
72+ for (int i = 0 ; i < dimension (); ++i ) {
73+ for (int j = 0 ; j < dimension (); ++j ) {
74+ if (tiles [i ][j ] != goalAt (i , j )) {
75+ return false ;
76+ }
77+ } }
78+ return true ;
4679 }
4780
4881 // does this board equal y?
4982 public boolean equals (Object y ) {
50- return false ;
83+ if (y == this ) return true ;
84+ if (y == null ) return false ;
85+ if (getClass () != y .getClass ()) return false ;
86+
87+ Board other = (Board ) y ;
88+ if (dimension () != other .dimension ()) return false ;
89+
90+ for (int i = 0 ; i < dimension (); ++i ) {
91+ for (int j = 0 ; j < dimension (); ++j ) {
92+ if (tiles [i ][j ] != other .tiles [i ][j ]) {
93+ return false ;
94+ }
95+ } }
96+ return true ;
5197 }
5298
5399 // all neighboring boards
@@ -64,4 +110,8 @@ public Board twin() {
64110 public static void main (String [] args ) {
65111 //
66112 }
113+
114+ private int goalAt (int i , int j ) {
115+ return i * n + j + 1 ;
116+ }
67117}
0 commit comments