1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
|
static class Node {
int r, c;
int[][] board;
Node(int r, int c , int[][] board) {
this.r = r;
this.c = c;
this.board = new int[3][3];
copyBoard(board, this.board);
}
}
static void copyBoard(int[][] src, int[][] dest) {
for (int i = 0; i < 3; i++)
System.arraycopy(src[i], 0, dest[i], 0, 3);
}
static void swap(int[][] arr, int r1, int c1, int r2, int c2) {
int tmp = arr[r1][c1];
arr[r1][c1] = arr[r2][c2];
arr[r2][c2] = tmp;
}
static Set<String> visited = new HashSet<>();
static int[][] input = new int[3][3];
static int sr, sc;
static int[] dx = {-1 , 0, 1, 0};
static int[] dy = { 0 ,-1, 0, 1};
static int bfs() {
Queue<Node> q = new ArrayDeque<>();
q.offer(new Node(sr, sc, input));
int cnt = 0;
while (!q.isEmpty()) {
int qSize = q.size();
for (int qs = 0; qs < qSize; qs++) {
Node cur = q.poll();
boolean isFin = true;
for (int i = 0; i < 8; i++)
if (cur.board[i/3][i%3] != i+1)
isFin = false;
if(isFin) return cnt;
for (int i = 0; i < 4; i++) {
int nr = cur.r + dx[i];
int nc = cur.c + dy[i];
if \(nr < 0 \|| nr >= 3 \|| nc < 0 \|| nc >= 3)
continue;
int[][] nextBoard = new int[3][3];
copyBoard(cur.board, nextBoard);
swap(nextBoard, cur.r, cur.c, nr, nc);
StringBuilder sb = new StringBuilder();
for (int j = 0; j < 9; j++)
sb.append(nextBoard[j/3][j%3]);
if (visited.contains(sb.toString()))
continue;
visited.add(sb.toString());
q.offer(new Node(nr, nc, nextBoard));
}
}
cnt++;
}
return -1;
}
|