题解 | #岛屿数量#
岛屿数量
http://www.nowcoder.com/practice/0c9664d1554e466aa107d899418e814e
import java.util.*;
public class Solution {
/**
m,n表示坐标,把与m和n相邻的1 都置为 0
*/
static void dfs(char[][] grid, int m, int n) {
if (m < 0 || n < 0 || m > grid.length || n > grid[0].length) {
return;
}
grid[m][n] = '0';
if (m > 0 && m < grid.length && grid[m - 1][n] == '1') {
dfs(grid, m - 1, n);
}
if (m >= 0 && m < grid.length - 1 && grid[m + 1][n] == '1') {
dfs(grid, m + 1, n);
}
if (n > 0 && n < grid[0].length && grid[m][n - 1] == '1') {
dfs(grid, m, n - 1);
}
if (n >= 0 && n < grid[0].length - 1 && grid[m][n + 1] == '1') {
dfs(grid, m, n + 1);
}
}
/**
* 判断岛屿数量
* @param grid char字符型二维数组
* @return int整型
*/
public int solve (char[][] grid) {
// write code here
//空矩阵
if (grid.length == 0) {
return 0;
}
int count = 0;//岛屿的数量
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
if (grid[i][j] == '1') {
count++;
dfs(grid, i, j);
}
}
}
return count;
}
}