题目地址:
https://www.lintcode.com/problem/island-city/description
给定一个二维矩阵,里面的数字都是,或者。将和视为等价,要求返回含的连通块个数。
思路是DFS,遍历的同时用一个boolean变量记录是否找到了,并将这个信息返回,最后累加含的连通块个数即可。代码如下:
public class Solution {
/**
* @param grid: an integer matrix
* @return: an integer
*/
public int numIslandCities(int[][] grid) {
// Write your code here
if (grid == null || grid.length == 0) {
return 0;
}
int res = 0;
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
if (grid[i][j] != -1 && dfs(i, j, grid)) {
res++;
}
}
}
return res;
}
private boolean dfs(int x, int y, int[][] grid) {
// 先初始化hasCity为false,后面再更新
boolean hasCity = false;
// 如果当前就是2,则更新hasCity
if (grid[x][y] == 2) {
hasCity = true;
}
// 标记为-1,这样以后就不用继续访问这个位置了
grid[x][y] = -1;
int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
for (int i = 0; i < dirs.length; i++) {
int nextX = x + dirs[i][0], nextY = y + dirs[i][1];
if (isValid(nextX, nextY, grid)) {
// 如果后面找到了2,也更新hasCity
hasCity |= dfs(nextX, nextY, grid);
}
}
return hasCity;
}
private boolean isValid(int x, int y, int[][] grid) {
return 0 <= x && x < grid.length && 0 <= y && y < grid[0].length && (grid[x][y] == 1 || grid[x][y] == 2);
}
}
时空复杂度。