class Solution {
public int slidingPuzzle(int[][] board) {
int res = 0;
String start = "";
String end = "123450";
for(int i = 0 ; i < board.length ; i ++ )
for( int j = 0 ; j < board[0].length ; j ++ )
start += board[i][j];
HashSet<String> visited = new HashSet<>();
Queue<String> queue = new LinkedList<>();
queue.offer(start);
visited.add(start);
int[][] dirs = new int[][]{{1, 3}, {0, 2, 4}, {1, 5}, {0, 4}, {1, 3, 5}, {2, 4}};
while( !queue.isEmpty() ){
int sz = queue.size();
for( int i = 0 ; i < sz ; i ++ ){
String cur = queue.poll();
if( cur.equals(end) )return res;
int zero = cur.indexOf('0');
for( int dir : dirs[zero] ){
String next = sswap(cur, zero, dir);
if( visited.contains(next))continue;
visited.add(next);
queue.offer(next);
}
}
res ++;
}
return -1;
}
private String sswap(String s, int i, int j){
StringBuilder sb = new StringBuilder(s);
sb.setCharAt(i, s.charAt(j));
sb.setCharAt(j, s.charAt(i));
return sb.toString();
}
}
在由一个已知的string构建stringbuilder时,构建语句为
StringBuilder sb = new StringBuilder(s);