1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
| public class ShortestBridge { public static int shortestBridge(int[][] arr) { List<int[]> firstLand = new ArrayList<>(); boolean[][] visited = new boolean[arr.length][arr[0].length]; boolean flag = false; for (int i = 0; i < arr.length; i++) { if (flag) { break; } for (int j = 0; j < arr[i].length; j++) { if (arr[i][j] == 1) { dfs(arr, i, j, visited, firstLand); flag = true; break; } } } int ans = Integer.MAX_VALUE; for (int[] xy : firstLand) { visited = new boolean[arr.length][arr[0].length]; ans = Math.min(ans, bfs(arr, xy[0], xy[1], visited));
} return ans; }
public static void dfs(int[][] arr, int x, int y, boolean[][] visited, List<int[]> firstLand) { if (x >= 0 && y >= 0 && x < arr.length && y < arr[0].length && !visited[x][y]) { visited[x][y] = true; if (arr[x][y] == 0) { return; } arr[x][y] = -1; firstLand.add(new int[]{x, y}); dfs(arr, x - 1, y, visited, firstLand); dfs(arr, x + 1, y, visited, firstLand); dfs(arr, x, y - 1, visited, firstLand); dfs(arr, x, y + 1, visited, firstLand); } }
public static int bfs(int[][] arr, int x, int y, boolean[][] visited) { int len = -1; Queue<int[]> queue = new LinkedList<>(); queue.offer(new int[]{x, y}); visited[x][y] = true; while (!queue.isEmpty()) { int limit = queue.size(); for (int i = 0; i < limit; i++) { int[] curr = queue.poll(); x = curr[0]; y = curr[1]; if (arr[x][y] == 1) { return len; } if (x - 1 >= 0 && !visited[x - 1][y] && arr[x - 1][y] != -1) { queue.offer(new int[]{x - 1, y}); visited[x - 1][y] = true; } if (x + 1 < arr.length && !visited[x + 1][y] && arr[x + 1][y] != -1) { queue.offer(new int[]{x + 1, y}); visited[x + 1][y] = true; } if (y - 1 >= 0 && !visited[x][y - 1] && arr[x][y - 1] != -1) { queue.offer(new int[]{x, y - 1}); visited[x][y - 1] = true; } if (y + 1 < arr[0].length && !visited[x][y + 1] && arr[x][y + 1] != -1) { queue.offer(new int[]{x, y + 1}); visited[x][y + 1] = true; } } len++; } return Integer.MAX_VALUE; } }
|