AcWing 845. 八数码BFS--Java
原题链接
中等
作者:
nq
,
2021-03-14 14:23:16
,
所有人可见
,
阅读 317
import java.io.*;
import java.util.*;
public class Main {
static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
private static int bfs(String str,String end)
{
Queue<String> q = new LinkedList<>();
Map<String,Integer> map = new HashMap<>();
int dx[] = {0,0,-1,1}, dy[] = {1,-1,0,0};
q.offer(str);
map.put(str , 0); //记录该状态和达到改状态的交换次数
while(!q.isEmpty())
{
String tmp = q.poll();
int dist = map.get(tmp);
int k = tmp.indexOf('x');
int x = k / 3 , y = k % 3; //找到'x'的坐标(x,y)
for(int i = 0 ; i < 4 ; i ++)
{
int px = x+dx[i] , py = y + dy[i];
if(px < 0 || px >= 3 || py < 0 || py >= 3 )continue;
//将(px,py)与(x,y)交换
char ch[] = tmp.toCharArray();
char c = ch[k];
ch[k] = ch[px * 3 + py];
ch[px * 3 + py] = c;
String new_str = String.valueOf(ch);
if(new_str.equals(end)) return dist + 1;
if(!map.containsKey(new_str)){
map.put(new_str , dist + 1);
q.offer(new_str);
}
}
}
return -1;
}
public static void main(String[] args) throws IOException
{
String str = in.readLine().replaceAll(" ","");
String end = "12345678x";
System.out.println(bfs(str,end));
}
}