publicint(int[][] A){ int result = 0; int m = A.length; int n = A[0].length; int[][] directions = newint[][] {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; Queue<int[]> queue = new LinkedList<>();
findIsland: for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (A[i][j] == 1) { dfs(queue, A, i, j, m, n); break findIsland; } } }
while (!queue.isEmpty()) { int size = queue.size();
for (int i = 0; i < size; i++) { int[] pos = queue.poll();
for (int[] direction : directions) { int x = pos[0] + direction[0]; int y = pos[1] + direction[1];
if (x < 0 || y < 0 || x >= m || y >= n || A[x][y] == 2) continue;
if (A[x][y] == 1) return result;
A[x][y] = 2; queue.offer(newint[] {x, y}); } }
result++; }
return -1; }
privatevoiddfs(Queue<int[]> queue, int[][] A, int x, int y, int m, int n){ if (x < 0 || y < 0 || x >= m || y >= n || A[x][y] != 1) return;
queue.offer(newint[] {x, y}); A[x][y] = 2; dfs(queue, A, x + 1, y, m, n); dfs(queue, A, x - 1, y, m, n); dfs(queue, A, x, y + 1, m, n); dfs(queue, A, x, y - 1, m, n); }
近期评论