DFS经典题,两种方法,递归或者用栈
1.递归
public class Solution
{
public int MaxAreaOfIsland(int[][] grid)
{
int rows = grid.Length;
int cols = grid[0].Length;
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;
}
private 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);
}
}
private int Max(int a, int b)
{
return a > b? a : b;
}
}
2.栈
public class Solution
{
public int MaxAreaOfIsland(int[][] grid)
{
int rows = grid.Length;
int cols = grid[0].Length;
int res = 0;
List<int[]> islandsStack = new List<int[]>();
for(int i = 0; i < rows; i++)
{
for(int j = 0; j < cols; j++)
{
if(grid[i][j] != 0)
{
islandsStack.Add(new int[2]{i,j});
int tempRes = 0;
while(islandsStack.Count != 0)
{
tempRes += 1;
int[] point = islandsStack[islandsStack.Count - 1];
islandsStack.RemoveAt(islandsStack.Count - 1);
grid[point[0]][point[1]] = 0;
if(point[0] + 1 < rows && grid[point[0] + 1][point[1]] != 0)
{
grid[point[0] + 1][point[1]] = 0;
islandsStack.Add(new int[2]{point[0] + 1, point[1]});
}
if(point[0]- 1 >= 0 && grid[point[0] - 1][point[1]] != 0)
{
grid[point[0] - 1][point[1]] = 0;
islandsStack.Add(new int[2]{point[0] - 1, point[1]});
}
if(point[1] + 1 < cols && grid[point[0]][point[1] + 1] != 0)
{
grid[point[0]][point[1] + 1] = 0;
islandsStack.Add(new int[2]{point[0], point[1]+ 1});
}
if(point[1] - 1 >= 0 && grid[point[0]][point[1] - 1] != 0)
{
grid[point[0]][point[1] - 1] = 0;
islandsStack.Add(new int[2]{point[0], point[1] - 1});
}
}
res = Max(res, tempRes);
}
}
}
return res;
}
private int Max(int a, int b)
{
return a > b? a : b;
}
}