994 . Oranges
unknown
plain_text
a year ago
1.1 kB
3
Indexable
Never
class Solution { public int orangesRotting(int[][] grid) { if(grid == null || grid.length == 0) return -1; for(int i=0; i<grid.length; i++) { for(int j=0; j<grid[0].length; j++) { if(grid[i][j] == 2) { dfs(i, j, grid, 2); } } } int minutes = 2; for(int[] row : grid) { for(int cell : row) { if(cell == 1) return -1; minutes = Math.max(minutes, cell); } } return minutes - 2; } private void dfs(int i, int j, int[][] grid, int minutes) { if(i < 0 || i >= grid.length || j < 0 || j >= grid[0].length || grid[i][j] == 0 || (1 < grid[i][j] && grid[i][j] < minutes) ) return; else { grid[i][j] = minutes; dfs(i - 1, j, grid, minutes + 1); dfs(i + 1, j, grid, minutes + 1); dfs(i, j - 1, grid, minutes + 1); dfs(i, j + 1, grid, minutes + 1); } } }