LeetCode 1730. Shortest Path to Get Food
原题链接在这里:https://leetcode.com/problems/shortest-path-to-get-food/
题目:
You are starving and you want to eat food as quickly as possible. You want to find the shortest path to arrive at any food cell.
You are given an m x n
character matrix, grid
, of these different types of cells:
'*'
is your location. There is exactly one'*'
cell.'#'
is a food cell. There may be multiple food cells.'O'
is free space, and you can travel through these cells.'X'
is an obstacle, and you cannot travel through these cells.
You can travel to any adjacent cell north, east, south, or west of your current location if there is not an obstacle.
Return the length of the shortest path for you to reach any food cell. If there is no path for you to reach food, return -1
.
Example 1:
Input: grid = [["X","X","X","X","X","X"],["X","*","O","O","O","X"],["X","O","O","#","O","X"],["X","X","X","X","X","X"]] Output: 3 Explanation: It takes 3 steps to reach the food.
Example 2:
Input: grid = [["X","X","X","X","X"],["X","*","X","O","X"],["X","O","X","#","X"],["X","X","X","X","X"]] Output: -1 Explanation: It is not possible to reach the food.
Example 3:
Input: grid = [["X","X","X","X","X","X","X","X"],["X","*","O","X","O","#","O","X"],["X","O","O","X","O","O","X","X"],["X","O","O","O","O","#","O","X"],["X","X","X","X","X","X","X","X"]] Output: 6 Explanation: There can be multiple food cells. It only takes 6 steps to reach the bottom food.
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 200
grid[row][col]
is'*'
,'X'
,'O'
, or'#'
.- The
grid
contains exactly one'*'
.
题解:
Perform BFS from the start and eventually find the food.
Time Complexity: O(m*n). m = grid.length. n = grid[0].length.
Space: O(m*n).
AC Java:
1 class Solution { 2 int [][] dirs = new int[][]{{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; 3 public int getFood(char[][] grid) { 4 int m = grid.length; 5 int n = grid[0].length; 6 LinkedList<int[]> que = new LinkedList<>(); 7 que.add(findStart(grid)); 8 boolean[][] visited = new boolean[m][n]; 9 10 int level = 0; 11 while(!que.isEmpty()){ 12 int size = que.size(); 13 while(size-- > 0){ 14 int [] cur = que.poll(); 15 if(grid[cur[0]][cur[1]] == '#'){ 16 return level; 17 } 18 19 for(int [] dir : dirs){ 20 int x = cur[0] + dir[0]; 21 int y = cur[1] + dir[1]; 22 if(x < 0 || x >= m || y < 0 || y >= n || grid[x][y] == 'X' || visited[x][y]){ 23 continue; 24 } 25 26 visited[x][y] = true; 27 que.add(new int[]{x, y}); 28 } 29 } 30 31 level++; 32 } 33 34 return -1; 35 } 36 37 private int[] findStart(char [][] grid){ 38 for(int i = 0; i < grid.length; i++){ 39 for(int j = 0; j < grid[0].length; j++){ 40 if(grid[i][j] == '*'){ 41 return new int[]{i, j}; 42 } 43 } 44 } 45 46 return new int[0]; 47 } 48 }
类似01 Matrix.