題目地址:
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);
}
}
時空複雜度。