AcWing 845. 八数码 Java 用现成的容器做
原题链接
中等
作者:
ac_ht6
,
2020-05-31 20:17:01
,
所有人可见
,
阅读 549
import java.util.*;
public class Main {
public static int bfs(String start) {
String end = "12345678x";
Queue<String> q = new LinkedList<>();
Map<String, Integer> d = new HashMap<>();
q.offer(start);
d.put(start, 0);
int[] dx = {-1,1,0,0};
int[] dy = {0,0,-1,1};
while(!q.isEmpty()) {
String t = q.poll();
if(t.equals(end)) return d.get(end);
int dis = d.get(t);
int k = t.indexOf('x');
for(int i = 0 ;i < 4; i++) {
int x = k / 3 + dx[i];
int y = k % 3 + dy[i];
if (x >= 0 && y >= 0 && x < 3 && y < 3) {
char[] chs = t.toCharArray();
char tmp = chs[k];
chs[k] = chs[x * 3 + y];
chs[x * 3 + y] = tmp;
String newStr = String.valueOf(chs);
if (d.get(newStr) == null) {
d.put(newStr, dis + 1);
q.offer(newStr);
}
}
}
}
return -1;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String start = "";
for(int i = 0; i < 9;i++) {
start += sc.next();
}
System.out.println(bfs(start));
}
}