1- import edu .princeton .cs .algs4 .StdOut ;
2-
31public class Board {
42 private int n ;
5- public int [][] tiles ;
3+ private int [][] tiles ;
64
75 // create a board from an n-by-n array of tiles,
86 // where tiles[row][col] = tile at (row, col)
97 public Board (int [][] tiles ) {
10- this .tiles = tiles ;
118 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- // }
9+ this . tiles = new int [ n ][ n ];
10+ for ( int i = 0 ; i < n ; ++ i )
11+ for (int j = 0 ; j < n ; ++j ) {
12+ this . tiles [ i ][ j ] = tiles [ i ][ j ] ;
13+ }
1714 }
1815
1916 // string representation of this board
@@ -40,19 +37,19 @@ public int dimension() {
4037 // number of tiles out of place
4138 public int hamming () {
4239 int cnt = 0 ;
43- for (int i = 0 ; i < dimension (); ++i ) {
40+ for (int i = 0 ; i < dimension (); ++i )
4441 for (int j = 0 ; j < dimension (); ++j ) {
4542 if (tiles [i ][j ] != goalAt (i , j )) {
4643 cnt ++;
4744 }
48- } }
45+ }
4946 return cnt ;
5047 }
5148
5249 // sum of Manhattan distances between tiles and goal
5350 public int manhattan () {
5451 int cnt = 0 ;
55- for (int i = 0 ; i < dimension (); ++i ) {
52+ for (int i = 0 ; i < dimension (); ++i )
5653 for (int j = 0 ; j < dimension (); ++j ) {
5754 int v = tiles [i ][j ];
5855 v = v == 0 ? n * n : v ;
@@ -63,18 +60,18 @@ public int manhattan() {
6360 int xy = Math .abs (y - i );
6461
6562 cnt += xd + xy ;
66- } }
63+ }
6764 return cnt ;
6865 }
6966
7067 // is this board the goal board?
7168 public boolean isGoal () {
72- for (int i = 0 ; i < dimension (); ++i ) {
69+ for (int i = 0 ; i < dimension (); ++i )
7370 for (int j = 0 ; j < dimension (); ++j ) {
7471 if (tiles [i ][j ] != goalAt (i , j )) {
7572 return false ;
7673 }
77- } }
74+ }
7875 return true ;
7976 }
8077
@@ -87,13 +84,15 @@ public boolean equals(Object y) {
8784 Board other = (Board ) y ;
8885 if (dimension () != other .dimension ()) return false ;
8986
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- } }
9687 return true ;
88+
89+ // for (int i = 0; i < dimension(); ++i) {
90+ // for (int j = 0; j < dimension(); ++j) {
91+ // if (tiles[i][j] != other.tiles[i][j]) {
92+ // return false;
93+ // }
94+ // } }
95+ // return true;
9796 }
9897
9998 // all neighboring boards
0 commit comments