-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathShortest Bridge.java
44 lines (40 loc) · 1.32 KB
/
Shortest Bridge.java
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
class Solution {
public int shortestBridge(int[][] grid) {
markGridTwo(grid);
for (int color = 2;; ++color)
for (int i = 0; i < grid.length; ++i)
for (int j = 0; j < grid[0].length; ++j)
if (grid[i][j] == color)
if (expand(grid, i + 1, j, color) || expand(grid, i - 1, j, color) ||
expand(grid, i, j + 1, color) || expand(grid, i, j - 1, color))
return color - 2;
}
// Marks one group to 2s by DFS.
private void markGridTwo(int[][] grid) {
for (int i = 0; i < grid.length; ++i)
for (int j = 0; j < grid[0].length; ++j)
if (grid[i][j] == 1) {
markGridTwo(grid, i, j);
return;
}
}
private void markGridTwo(int[][] grid, int i, int j) {
if (i < 0 || i == grid.length || j < 0 || j == grid[0].length)
return;
if (grid[i][j] != 1)
return;
grid[i][j] = 2;
markGridTwo(grid, i + 1, j);
markGridTwo(grid, i - 1, j);
markGridTwo(grid, i, j + 1);
markGridTwo(grid, i, j - 1);
}
// Returns true if we touch 1s' group through expanding.
private boolean expand(int[][] grid, int i, int j, int color) {
if (i < 0 || i == grid.length || j < 0 || j == grid[0].length)
return false;
if (grid[i][j] == 0)
grid[i][j] = color + 1;
return grid[i][j] == 1;
}
}