Time Limit: 1000MS | Memory Limit: 65536K | |||
Total Submissions: 21718 | Accepted: 9611 | Special Judge |
Description
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 x
1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 5 6 7 8 5 6 7 8 5 6 7 8 5 6 7 8 9 x 10 12 9 10 x 12 9 10 11 12 9 10 11 12 13 14 11 15 13 14 11 15 13 14 x 15 13 14 15 x r-> d-> r->
Input
1 2 3 x 4 6 7 5 8
1 2 3 x 4 6 7 5 8
Output
Sample Input
2 3 4 1 5 x 7 6 8
Sample Output
ullddrurdllurdruldr
/* * 感言:广搜,题不是太标准,搜索方向顺序不同,结果不同, * 不过可以AC,但是有可能会超时 * */ import java.util.ArrayDeque; import java.util.HashMap; import java.util.Map; import java.util.Queue; import java.util.Scanner; public class Main{ static Map<String,Integer> map=new HashMap<String, Integer>(); static Queue<BFS> q=new ArrayDeque<BFS>(); static String end="12345678x"; static char g[]=new char[]{'u','l','d','r'}; static int d[][]=new int[][]{{-1,0},{0,-1},{1,0},{0,1}};//方向不同结果不同 public static void main(String[] args) { Scanner input=new Scanner(System.in); String s[][]=new String[3][3]; while(input.hasNext()){ map.clear(); q.clear(); BFS text=new BFS(); for(int i=0;i<3;i++){ for(int j=0;j<3;j++){ s[i][j]=input.next(); if(s[i][j].equals("x")){ text.setX(i); text.setY(j); } } } text.setS(s); map.put(text.getKey(), 0); q.add(text); System.out.println(bfs(q)); } } private static String bfs(Queue<BFS> q2) { while(!q2.isEmpty()){ BFS text=q2.poll(); if(end.equals(text.getKey())){ return text.getPath().toString(); } for(int i=0;i<4;i++){ int x=text.getX()+d[i][0]; int y=text.getY()+d[i][1]; if(x<0||x>=3||y<0||y>=3) continue; String f[][]=text.copys(); f[text.getX()][text.getY()]=f[x][y]; f[x][y]="x"; BFS st=new BFS(); st.setX(x); st.setY(y); st.setS(f); st.getPath().append(text.getPath()).append(g[i]); String key=st.getKey(); if(!map.containsKey(key)){ q2.add(st); map.put(key, 0); } } } return "unsolvable"; } } class BFS{ private Integer x,y; private String s[][]; private StringBuilder path=new StringBuilder(); public String[][] copys(){ String c[][]=new String[3][3]; for(int i=0;i<3;i++) for(int j=0;j<3;j++){ c[i][j]=s[i][j]; } return c; } public String getKey(){ StringBuilder a=new StringBuilder(); for(int i=0;i<3;i++){ for(int j=0;j<3;j++){ a.append(s[i][j]); } } return a.toString(); } public int getX() { return x; } public void setX(int x) { this.x = x; } public int getY() { return y; } public void setY(int y) { this.y = y; } public String[][] getS() { return s; } public void setS(String[][] s) { this.s = s; } public StringBuilder getPath() { return path; } public void setPath(StringBuilder path) { this.path = path; } }