You could use UnionFind, I just don't bother doing it.
As the islands are not dynamic UnionFind is unnecessary.
Just use plain old DFS, trigger it with a simple scan for cities that's not visited,
Then count the number of triggers.
Boom!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Solution { | |
/** | |
* @param grid: an integer matrix | |
* @return: an integer | |
*/ | |
int numIslandCities(int[][] A) { | |
// filter abnormal cases | |
if (A == null || A.length == 0) { | |
return 0; | |
} | |
this.m = A.length; | |
this.n = A[0].length; | |
this.A = A; | |
this.visited = new boolean[m][n]; | |
int counter = 0; | |
for (int i = 0; i < m; i++) { | |
for (int j = 0; j < n; j++) { | |
if (A[i][j] == 2 && !visited[i][j]) { | |
dfs(i, j); | |
counter++; | |
} | |
} | |
} | |
// return the final result | |
return counter; | |
} | |
int[][] A; | |
boolean[][] visited; | |
int m; | |
int n; | |
private void dfs(int i, int j) { | |
if (i < 0 || j < 0 || i >= m || j >= n) { | |
return; | |
} | |
if (A[i][j] == 0) { | |
return; | |
} | |
if (visited[i][j]) { | |
return; | |
} | |
visited[i][j] = true; | |
A[i][j] = 2; | |
dfs(i - 1, j); | |
dfs(i + 1, j); | |
dfs(i, j - 1); | |
dfs(i, j + 1); | |
} | |
} |
No comments:
Post a Comment