如何使用 C# 打印给定矩阵中的岛数?
线性扫描二维网格图,如果一个节点包含'1',那么它是触发深度优先搜索的根节点。在DFS期间,每个访问过的节点都应设置为“0”以标记为访问过的节点。计算触发DFS的根节点的数量,这个数字就是岛的数量,因为从某个根开始的每个DFS标识一个岛。
示例
using System;
namespace ConsoleApplication{
public class Matrix{
public int PrintNumberOfIslands(char[,] grid){
bool[,] visited = new bool[grid.GetLength(0), grid.GetLength(1)];
int res = 0;
for (int i = 0; i < grid.GetLength(0); i++){
for (int j = 0; j < grid.GetLength(1); j++){
if (grid[i, j] == '1' && !visited[i, j]){
DFS(grid, visited, i, j);
res++;
}
}
}
return res;
}
public void DFS(char[,] grid, bool[,] visited, int i, int j){
if (i < 0 || i >= grid.GetLength(0)) return;
if (j < 0 || j >= grid.GetLength(1)) return;
if (grid[i, j] != '1' || visited[i, j]) return;
visited[i, j] = true;
DFS(grid, visited, i + 1, j);
DFS(grid, visited, i - 1, j);
DFS(grid, visited, i, j + 1);
DFS(grid, visited, i, j - 1);
}
}
class Program{
static void Main(string[] args){
Matrix m = new Matrix();
char[,] mm = { { '1', '1', '1', '1', '0' }, { '1', '1', '0', '1', '0' }, { '1', '1', '0', '0', '0' }, { '0', '0', '0', '0', '1' } };
Console.WriteLine(m.PrintNumberOfIslands(mm));
}
}
}输出结果2
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短