package top100.图论;
import java.util.LinkedList;
import java.util.Queue;
public class TOP {
int[][] ways = new int[][]{{-1, 0}, {1, 0}, {0, 1}, {0, -1}};
public int numIslands(char[][] grid) {
int m = grid.length, n = grid[0].length;
int res = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == '1') {
res++;
dfs(grid, i, j, m, n);
}
}
}
return res;
}
private void dfs(char[][] grid, int i, int j, int m, int n) {
grid[i][j] = '0';
for (int[] way : ways) {
int x = i + way[0], y = j + way[1];
if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == '1') {
dfs(grid, x, y, m, n);
}
}
}
public int orangesRotting(int[][] grid) {
int m = grid.length;
int n = grid[0].length;
int fresh = 0;
Queue<int[]> queue = new LinkedList<>();
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == 1) {
fresh++;
} else if (grid[i][j] == 2) {
queue.add(new int[]{i, j});
}
}
}
int[][] ways = new int[][]{{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
int res = 0;
while (fresh > 0 && !queue.isEmpty()) {
res++;
int k = queue.size();
for (int i = 0; i < k; i++) {
int[] cur = queue.poll();
for (int[] way : ways) {
int x = cur[0] + way[0];
int y = cur[1] + way[1];
if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == 1) {
fresh--;
grid[x][y] = 2;
queue.add(new int[]{x, y});
}
}
}
}
if (fresh > 0) {
return -1;
} else {
return res;
}
}
}