publicintorangesRotting(int[][] grid){ int n = grid.length; int m = grid[0].length; Queue<int[]> queue = new LinkedList<>(); int target = n * m; for (int i=0; i<n; ++i) { for (int j=0; j<m; ++j) { if (grid[i][j] == 2) { queue.offer(newint[]{i, j}); } elseif(grid[i][j] == 0) { target--; } } } if (target == 0) return0; int minute = 0; int[][] directions = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; while (!queue.isEmpty()) { int count = queue.size(); target -= count; if (target == 0) return minute; for (int i=0; i<count; ++i) { int[] cur = queue.poll(); for (int[] direction : directions) { int x = cur[0] + direction[0]; int y = cur[1] + direction[1]; if (x >= 0 && x < n && y >= 0 && y < m && grid[x][y] == 1) { queue.offer(newint[]{x, y}); grid[x][y] = 2; } } } minute++; } return -1; }
publicvoidwallsAndGates(int[][] rooms){ int n = rooms.length; int m = rooms[0].length; Queue<int[]> queue = new LinkedList<>(); for (int i=0; i<n; ++i) { for (int j=0; j<m; ++j) { if (rooms[i][j] == 0) { queue.offer(newint[]{i, j}); } } } int distance = 1; finalint INF = 2147483647; int[][] directions = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; while (true) { int cnt = queue.size(); if (cnt == 0) break; while (cnt > 0) { cnt--; int[] cur = queue.poll(); for (int[] direction : directions) { int[] next = {cur[0] + direction[0], cur[1] + direction[1]}; int x = next[0]; int y = next[1]; if (x >= 0 && x < n && y >= 0 && y < m && rooms[x][y] == INF) { rooms[x][y] = distance; queue.offer(next); } } } distance++; } }