题目

You are given an m x n binary matrix grid. An island is a group of 1‘s (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.

The area of an island is the number of cells with a value 1 in the island.

Return the maximum area of an island in grid. If there is no island, return 0.

Example 1:

image.png

  1. Input: grid = [[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,0,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]]
  2. Output: 6
  3. Explanation: The answer is not 11, because the island must be connected 4-directionally.

Example 2:

  1. Input: grid = [[0,0,0,0,0,0,0,0]]
  2. Output: 0

Constraints:

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 50
  • grid[i][j] is either 0 or 1.

题意

给定一个矩阵,0代表水,1代表岛,一个岛与垂直和水平方向相邻的岛组成一个更大的岛,求最大的岛的面积。

思路

直接DFS找每一个岛区域的大小即可。


代码实现

Java

  1. class Solution {
  2. private int m, n;
  3. private int[] xShift = {-1, 0, 1, 0};
  4. private int[] yShift = {0, -1, 0, 1};
  5. public int maxAreaOfIsland(int[][] grid) {
  6. int ans = 0;
  7. m = grid.length;
  8. n = grid[0].length;
  9. boolean[][] visited = new boolean[m][n];
  10. for (int x = 0; x < m; x++) {
  11. for (int y = 0; y < n; y++) {
  12. if (grid[x][y] == 1 && !visited[x][y]) {
  13. ans = Math.max(ans, dfs(grid, x, y, visited));
  14. }
  15. }
  16. }
  17. return ans;
  18. }
  19. private int dfs(int[][] grid, int x, int y, boolean[][] visited) {
  20. int cnt = 1;
  21. visited[x][y] = true;
  22. for (int i = 0; i < 4; i++) {
  23. int nx = x + xShift[i];
  24. int ny = y + yShift[i];
  25. if (nx >= 0 && nx < m && ny >= 0 && ny < n && grid[nx][ny] == 1 && !visited[nx][ny]) {
  26. cnt += dfs(grid, nx, ny, visited);
  27. }
  28. }
  29. return cnt;
  30. }
  31. }