| 1 | class Solution { |
| 2 | public int shortestBridge(int[][] grid) { |
| 3 | Queue<int[]> q = new LinkedList<>(); |
| 4 | boolean[][] vis = new boolean[grid.length][grid[0].length]; |
| 5 | |
| 6 | for (int i = 0; i < grid.length; i++) { |
| 7 | for (int j = 0; j < grid[0].length; j++) { |
| 8 | if (grid[i][j] == 1) { |
| 9 | mark(grid, vis, q, i, j); |
| 10 | i = grid.length; |
| 11 | j = grid[0].length; |
| 12 | } |
| 13 | } |
| 14 | } |
| 15 | int count = 0; |
| 16 | int[][] dir = {{0,1}, {1,0}, {-1,0}, {0,-1}}; |
| 17 | |
| 18 | while (!q.isEmpty()) { |
| 19 | int n = q.size(); |
| 20 | |
| 21 | for (int k = 0; k < n; k++) { |
| 22 | int[] curr = q.poll(); |
| 23 | |
| 24 | for (int j = 0; j < 4; j++) { |
| 25 | int r = curr[0] + dir[j][0]; |
| 26 | int c = curr[1] + dir[j][1]; |
| 27 | |
| 28 | if (r >= 0 && c >= 0 && r < grid.length && c < grid[0].length && !vis[r][c]) { |
| 29 | if (grid[r][c] == 1) return count; |
| 30 | vis[r][c] = true; |
| 31 | q.offer(new int[]{r,c}); |
| 32 | } |
| 33 | } |
| 34 | } |
| 35 | count++; |
| 36 | } |
| 37 | return -1; |
| 38 | } |
| 39 | |
| 40 | void mark(int[][] grid, boolean[][] vis , Queue<int[]> q, int i, int j) { |
| 41 | if (i < 0 || j < 0 || i >= grid.length || j >= grid[0].length || grid[i][j] == 0 || vis[i][j]) return; |