题解 | 走迷宫

走迷宫

https://www.nowcoder.com/practice/e88b41dc6e764b2893bc4221777ffe64

import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {    
    
    static int[]dx = {0,0,1,-1}, dy={1,-1,0,0};// 上下左右四个方向
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt(), m = in.nextInt();
        in.nextLine();
        String[] s1 = in.nextLine().split(" ");
        int stx = Integer.parseInt(s1[0])-1, sty = Integer.parseInt(s1[1])-1,
             enx = Integer.parseInt(s1[2])-1, eny = Integer.parseInt(s1[3])-1;// start and end
        char[][] arr = new char [n][m];
        for(int i=0;i<n;++i){            
            arr[i] = in.nextLine().toCharArray();                        
        }
        if(arr[stx][sty] == '*'||arr[enx][eny]=='*'){
            System.out.println(-1);
            return ;
        }

        Queue<int[]>  queue=new LinkedList<>();
        int[] node = {0, stx, sty};
        queue.add(node);
        int result = minStep(n,m,arr,enx,eny,queue);
        System.out.println(result);
    }

    static int minStep(int n,int m,char[][] arr, int enx, int eny, Queue<int[]> queue){
        while(queue.size()!=0){
            int[] node = queue.poll();
            int step = node[0];
            int x = node[1];
            int y = node[2];                
            if(x == enx&&y == eny)  return step;
            for(int i = 0;i<4;++i){
                int xx = x + dx[i];
                int yy = y + dy[i];
                if(check(arr, xx, yy, n, m)){
                    queue.add(new int[]{step+1, xx, yy});
                    arr[xx][yy] = '/';
                }
            }
        }
        return -1;
    }
    static boolean check(char[][] arr, int x, int y, int n, int m){
        return !(x < 0 || x >=n||y<0||y>=m||arr[x][y] != '.');
    }
}

全部评论

相关推荐

牛客96763241...:杭电✌️也是打完招呼,没人回吗
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务