This is a easier common grap and look for shortest path problem, time complexity: O(m*n):

class Solution {
    public int getFood(char[][] grid) {
        int m = grid.length, n = grid[0].length;
        int[][] dirs = new int[][]{{0,1},{0,-1},{1,0},{-1,0}};
        boolean[][] visited = new boolean[m][n];
        Queue<int[]> queue = new LinkedList<>();
        int[] people = findPeople(grid, m, n);
        
        queue.offer(people);
        visited[people[0]][people[1]]=true;
        int res=0;
        while(!queue.isEmpty()){
            int size = queue.size();
            for(int i=0;i<size;i++){
                int[] cell = queue.poll();
                int x = cell[0], y = cell[1];
                if(grid[x][y] == '#')
                    return res;
                for(int[] dir:dirs){
                    int newX = x+dir[0];
                    int newY = y+dir[1];
                    if(newX<0 || newX>=m || newY<0 ||newY>=n || grid[newX][newY]=='X' || visited[newX][newY])
                        continue;
                    queue.offer(new int[]{newX,newY});
                     visited[newX][newY]=true;
                    
                }
            }
            res++;
        }
        return -1;
    }
    
    private int[] findPeople(char[][] grid, int m, int n){
        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++){
                if(grid[i][j]=='*'){
                   return new int[]{i,j};
                 }
            }
        }
        return null;
    }
}

 

posted on 2022-03-05 15:02  阳光明媚的菲越  阅读(25)  评论(0编辑  收藏  举报