阿里笔试第二场 第二题
各位大佬可以帮忙找下bug吗,笔试时写了一份dfs,今天写了一份bfs,都有bug,好像都错在fly那里,但就是找不出来😣😣哭辽
dfs
#阿里笔试##LINE#public class Main1 { public static int n; public static int m; public static int minCost =Integer.MAX_VALUE; public static boolean [][]book; public static char a[][]; public static void main(String[] args) { Scanner scanner = new Scanner(System.in); n=scanner.nextInt(); m=scanner.nextInt(); a=new char[n][m]; book=new boolean[n][m]; scanner.nextLine(); for(int i=0;i<n;i++){ String tmp=scanner.nextLine(); for(int j=0;j<m;j++){ a[i][j]=tmp.charAt(j); } } for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ if(a[i][j]=='S'){ dfs(i,j,0,5); } } } System.out.println(minCost==Integer.MAX_VALUE?-1:minCost); // System.out.println(4); } static int visitX[]=new int[]{0,0,1,-1}; static int visitY[]=new int[]{1,-1,0,0}; public static void dfs(int i,int j,int curCost,int flyCount){ if(i<0||i>=n||j<0||j>=m||book[i][j]||a[i][j]=='#') return; if(a[i][j]=='E'){ minCost=Math.min(minCost,curCost); return; } book[i][j]=true; for(int k=0;k<4;k++){ int x=i+visitX[k]; int y=j+visitY[k]; dfs(x,y,curCost+1,flyCount); } if(flyCount>0){ int x=n+1-i; int y=m+1-j; dfs(x,y,curCost+1,flyCount-1); } book[i][j]=false; } }bfs
class Main2{ static class Node{ int x; int y; int flyCount; public Node(int x, int y, int flyCount) { this.x = x; this.y = y; this.flyCount = flyCount; } } public static int n; public static int m; public static boolean [][]book; public static char a[][]; static int visitX[]=new int[]{0,0,1,-1}; static int visitY[]=new int[]{1,-1,0,0}; public static void main(String[] args) { Scanner scanner = new Scanner(System.in); n=scanner.nextInt(); m=scanner.nextInt(); a=new char[n][m]; book=new boolean[n][m]; scanner.nextLine(); for(int i=0;i<n;i++){ String tmp=scanner.nextLine(); for(int j=0;j<m;j++){ a[i][j]=tmp.charAt(j); } } Node node=new Node(-1,-1,-1); for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ if(a[i][j]=='S'){ node=new Node(i,j,5); } } } Queue<Node> queue=new LinkedList<>(); queue.add(node); book[node.x][node.y]=true; int path=0; while (!queue.isEmpty()){ int size=queue.size(); while (size--!=0){ Node tmp=queue.poll(); if (a[tmp.x][tmp.y]=='E') { System.out.println(path); return; } for(int k=0;k<4;k++){ int x=tmp.x+visitX[k]; int y=tmp.y+visitY[k]; if(check(x,y)){ Node cur=new Node(x,y,tmp.flyCount); queue.add(cur); book[x][y]=true; } } if(tmp.flyCount>0){//飞跃 int x=n+1-tmp.x; int y=m+1-tmp.y; if(check(x,y)){ Node cur=new Node(x,y,tmp.flyCount-1); queue.add(cur); book[x][y]=true; } } } path++; } System.out.println(-1); } public static boolean check(int i,int j){ if(i<0||i>=n||j<0||j>=m||book[i][j]||a[i][j]=='#') return false; return true; } }