给你一个大小为 m x n 的二进制矩阵 grid 。
岛屿 是由一些相邻的 1 (代表土地) 构成的组合,这里的「相邻」要求两个 1 必须在 水平或者竖直的四个方向上 相邻。你可以假设 grid 的四个边缘都被 0(代表水)包围着。
岛屿的面积是岛上值为 1 的单元格的数目。
计算并返回 grid 中最大的岛屿面积。如果没有岛屿,则返回面积为 0 。
using System;
using System.Collections.Generic;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
int[,] nums = null;
nums = new int[,]{
{ 0,0,1,0,0,0,0,1,0,0,0,0,0},
{ 0,0,0,0,0,0,0,1,1,1,0,0,0},
{ 0,1,1,0,1,0,0,0,0,0,0,0,0},
{ 0,1,0,0,1,1,0,0,1,0,1,0,0},
{ 0,1,0,0,1,1,0,0,1,1,1,0,0},
{ 0,0,0,0,0,0,0,0,0,1,1,0,0},
{ 0,0,0,0,0,0,0,1,1,1,0,0,0},
{ 0,0,0,0,0,0,0,1,1,0,0,0,0} };
for (int i = 0; i < nums.Length; i++)
{
}
Console.WriteLine("行=" + nums.GetLength(0) + " " + "列=" + nums.GetLength(1));
Console.WriteLine("最大岛屿个数=" + MaxAreaOfIsland(nums));
Console.Read();
}
static int MaxAreaOfIsland(int[,] grid)
{
int rows = grid.GetLength(0);
int cols = grid.GetLength(1);
int res = 0;
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
res = Max(res, DFS(grid, i, j, rows, cols));
}
}
return res;
}
static int DFS(int[,] grid, int row, int col, int maxRow, int maxCol)
{
if (row < 0 || row >= maxRow || col < 0 || col >= maxCol || grid[row, col] == 0)
return 0;
else
{
grid[row, col] = 0;
return 1 + DFS(grid, row - 1, col, maxRow, maxCol) + DFS(grid, row + 1, col, maxRow, maxCol) + DFS(grid, row, col - 1, maxRow, maxCol) + DFS(grid, row, col + 1, maxRow, maxCol);
}
}
static int Max(int a, int b)
{
return a > b ? a : b;
}
}
}