一、题目
力扣200 岛屿数量
给你一个由 '1'(陆地)和 '0'(水)组成的的二维网格,请你计算网格中岛屿的数量。
岛屿总是被水包围,并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。
此外,你可以假设该网格的四条边均被水包围。
class Solution {
int m;
int n;
public int numIslands(char[][] grid) {
m = grid.length;
n = grid[0].length;
int count = 0;
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
if(grid[i][j] == '1'){
count++;
dfs(grid, i, j);
}
}
}
return count;
}
public void dfs(char[][] grid, int i, int j){
if(i < 0 || i >= m || j < 0 || j >= n){
return;
}
if(grid[i][j] == '0'){
return;
}
grid[i][j] = '0';
dfs(grid, i - 1, j);
dfs(grid, i + 1, j);
dfs(grid, i, j - 1);
dfs(grid, i, j + 1);
}
}
二、总结
1 矩阵的行/列问题
创建如下二维数组。
char[][] grid = {
{'0', '1', '2', '3', '4'},
{'5', '6', '7', '8', '9'},
{'A', 'B', 'C', 'D', 'E'},
{'F', 'G', 'H', 'I', 'J'}
};
grid[i][j] 表示该二维数组第 i 行第 j 列的值,如 grid[3][4] 为 'J',grid[4][3] 发生越界。
i 的取值区间为 [0, grid.length),j 的取值区间为 [0, grid[0].length]。
2 Flood Fill 算法
洪水填充算法,将统计过的岛屿沉入水中,避免统计重复。
三、练习题
查找单入口空闲区域
示例:
题解:
import java.util.Scanner;
public class Main {
static int m;
static int n;
static char[][] c2s;
static int resX = -1;
static int resY = -1;
static int resMax = -1;
static boolean beyondOne = false;
static int count;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
m = in.nextInt();
n = in.nextInt();
c2s = new char[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
c2s[i][j] = in.next().charAt(0);
}
}
work();
}
public static void work() {
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (c2s[i][j] == 'O' && isBound(i, j)) {
count = 0;
dfs(i, j);
if (count == resMax) {
beyondOne = true;
}
if (count > resMax) {
beyondOne = false;
resMax = count;
resX = i;
resY = j;
}
}
}
}
if (resMax <= 0) {
System.out.println("NULL");
} else if (beyondOne) {
System.out.println(resMax);
} else {
System.out.println(resX + " " + resY + " " + resMax);
}
}
public static void dfs(int i, int j) {
if (i < 0 || i >= m || j < 0 || j >= n) {
return;
}
if (c2s[i][j] == 'X') {
return;
}
if (count != 0 && isBound(i, j)) {
count = Integer.MIN_VALUE;
}
c2s[i][j] = 'X';
count++;
dfs(i - 1, j);
dfs(i + 1, j);
dfs(i, j - 1);
dfs(i, j + 1);
}
public static boolean isBound(int i, int j) {
return i == 0 || i == m - 1 || j == 0 || j == n - 1;
}
}