标签:put main ++ can import imp 路径 col char
int maze[5][5] = {
0, 1, 0, 0, 0,
0, 1, 0, 1, 0,
0, 0, 0, 0, 0,
0, 1, 1, 1, 0,
0, 0, 0, 1, 0,
};
Input
Output
Sample Input
0 1 0 0 0 0 1 0 1 0 0 0 0 0 0 0 1 1 1 0 0 0 0 1 0
Sample Output
(0, 0) (1, 0) (2, 0) (2, 1) (2, 2) (2, 3) (2, 4) (3, 4) (4, 4)
路径记录方式:dir[x][y]数组记录方向UDLR,然后逆向记录下路径
代码:
import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Scanner; class Node{ int x; int y; public Node(int x,int y){ this.x=x; this.y=y; } } public class Main{ static final int N=10; static int map[][]=new int[N][N]; static char dir[][]=new char[N][N]; static ArrayDeque<Node> q=new ArrayDeque<Node>(); static int dx[]={0,0,1,-1}; static int dy[]={1,-1,0,0}; static boolean flag=false; static void bfs(){ map[0][0]=1; q.offer(new Node(0,0)); while(!q.isEmpty()){ Node t=q.poll(); for(int i=0;i<4;i++){ int xx=t.x+dx[i]; int yy=t.y+dy[i]; if(xx<0||yy<0||xx>=5||yy>=5||map[xx][yy]==1) continue; map[xx][yy]=1; q.offer(new Node(xx,yy)); if(i==0){ dir[xx][yy]=‘R‘; } else if(i==1){ dir[xx][yy]=‘L‘; } else if(i==2){ dir[xx][yy]=‘D‘; } else{ dir[xx][yy]=‘U‘; } if(t.x==4 && t.y==4){ flag=true; break; } } if(flag) break; } ArrayList<Node> v=new ArrayList<Node>(); int i=4,j=4; while(i!=0 ||j!=0){ v.add(new Node(i,j)); if(dir[i][j]==‘R‘){ j=j-1; } else if(dir[i][j]==‘L‘){ j=j+1; } else if(dir[i][j]==‘D‘){ i=i-1; } else{ i=i+1; } } System.out.println("(0, 0)"); for(int k=v.size()-1;k>=0;k--){ Node s=v.get(k); System.out.println("("+s.x+", "+s.y+")"); } } public static void main(String[] args) { Scanner scan=new Scanner(System.in); for(int i=0;i<5;i++) for(int j=0;j<5;j++) map[i][j]=scan.nextInt(); bfs(); } }
标签:put main ++ can import imp 路径 col char
原文地址:https://www.cnblogs.com/qdu-lkc/p/12247786.html