文章目录
题目描述
思路
该问题可以归纳为一类遍历二维矩阵的题目,此类中的一部分题目可以利用DFS来解决,具体到本题目:
解题方法
复杂度
时间复杂度:
空间复杂度:
Code
class Solution {
private boolean[][] visited;
private int row;
private int col;
/**
* Get all the island counts
*
* @param grid Given a two-dimensional array
* @return int
*/
public int numIslands(char[][] grid) {
row = grid.length;
col = grid[0].length;
visited = new boolean[row][col];
//The count of island
int count = 0;
for (int i = 0; i < row; ++i) {
for (int j = 0; j < col; ++j) {
if (visited[i][j] != true && grid[i][j] == '1') {
count++;
dfs(grid, i, j);
}
}
}
return count;
}
/**
* Try dfs or not from each point in a two-dimensional array
*
* @param grid Given a two-dimensional array
* @param i Abscissa
* @param j Ordinate
*/
private void dfs(char[][] grid, int i, int j) {
//Record four bearings
int[][] directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
//The current legal location is set to true
visited[i][j] = true;
for (int k = 0; k < 4; ++k) {
int newI = i + directions[k][0];
int newJ = j + directions[k][1];
if (newI >= 0 && newI < row && newJ >= 0 && newJ < col
&& visited[newI][newJ] == false && grid[newI][newJ] == '1') {
dfs(grid, newI, newJ);
}
}
}
}