import java.util.Deque; import java.util.LinkedList; class node{ int x; int y; } class Solution{ private int dir[][]=new int[][] {{0,-1},{-1,0},{0,1},{1,0}}; private node parentx[][]; private int Count[][]; private boolean used[][]; private node start=new node(); private node end=new node(); private Deque<node> queue=new LinkedList<node>(); private node temp; private boolean flag=false; public boolean isCheckMove(String[] map,node start) { return start.x>=0&&start.x<map.length&&start.y>=0&&start.y<map[start.x].length(); } public boolean printPath(String[] map) { while(parentx[temp.x][temp.y].x!=temp.x||parentx[temp.x][temp.y].y!=temp.y) { System.out.print(map[temp.x].charAt(temp.y)+"->"); temp=parentx[temp.x][temp.y]; } System.out.println(map[temp.x].charAt(temp.y)); return true; } public int dfs(String[] map,node start) { queue.offer(start); used[start.x][start.y]=true; Count[start.x][start.y]=1; while(!queue.isEmpty()) { start=queue.pop(); for(int i=0;i<4;++i) { temp=new node(); temp.x=start.x+dir[i][0]; temp.y=start.y+dir[i][1]; if(temp.x==end.x&&temp.y==end.y) { flag=true; queue.addLast(temp); parentx[temp.x][temp.y]=start; Count[temp.x][temp.y]=Count[start.x][start.y]+1; used[temp.x][temp.y]=true; break; } if(isCheckMove(map,temp)&&!used[temp.x][temp.y]) { queue.addLast(temp); parentx[temp.x][temp.y]=start; Count[temp.x][temp.y]=Count[start.x][start.y]+1; used[temp.x][temp.y]=true; } } if(flag) { break; } } return Count[temp.x][temp.y]; } public boolean nums(String map[]) { queue.clear(); parentx=new node[map.length][map[0].length()]; Count=new int[map.length][map[0].length()]; used=new boolean[map.length][map[0].length()]; for(int i=0;i<map.length;++i) { for(int j=0;j<map[i].length();++j) { used[i][j]=false; Count[i][j]=0; node tmp=new node(); tmp.x=i; tmp.y=j; parentx[i][j]=tmp; if(map[i].charAt(j)=='#') { end.x=i; end.y=j; } if(map[i].charAt(j)=='@') { start.x=i; start.y=j; } } } System.out.println(dfs(map,start)); printPath(map); return true; } } public class First{ public static void main(String[] args) { Solution space = new Solution(); String map[]= {"****","@***","&&&&","&&&&","&#**"}; space.nums(map); for(String str:map) { System.out.println(str); } } }