695. Max Area of Island(dfs)
Given a non-empty 2D array grid
of 0’s and 1’s, 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.
Find the maximum area of an island in the given 2D array. (If there is no island, the maximum area is 0.)
Example 1:
[[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]]
Given the above grid, return 6
. Note the answer is not 11, because the island must be connected 4-directionally.
Example 2:
[[0,0,0,0,0,0,0,0]]
Given the above grid, return 0
.
Note: The length of each dimension in the given grid
does not exceed 50.
题目意思是1表示一块地,要我们找出这个由一连在一起的总的地是多大。就是全都相连的1的个数有多少个
这题可以用深搜来做,从0,0开始到最后一个index开始遍历,每个index我们都用dfs来搜一遍
dfs中让该index从上下左右四个方向来搜索,判断跳出递归条件就是index不在范围之内了,或者是这块地我们已经搜过了还有就是这处index根本不是land
if (x>=grid.length || x<0 || y>=grid[0].length || y<0 || seen[x][y] || grid[x][y]==0) {
return 0;
}
public class MaxArea {
static boolean seen[][];
public int maxAreaOfIsland(int[][] grid) {
seen = new boolean[grid.length][grid[0].length];
int ans = 0;
for (int i=0; i<grid.length; i++) {
for (int j=0; j<grid[0].length; j++) {
ans = Math.max(ans, dfs(i, j, grid));
}
}
return ans;
}
static int dfs(int x, int y, int grid[][]) {
int num = 0;
if (x>=grid.length || x<0 || y>=grid[0].length || y<0 || seen[x][y] || grid[x][y]==0) {
return 0;
}
if (seen[x][y]==false && grid[x][y]==1) {
seen[x][y] = true;
num += 1;
num += dfs(x-1, y, grid);
num += dfs(x+1, y, grid);
num += dfs(x, y+1, grid);
num += dfs(x, y-1, grid);
}
return num;
}
public static void main(String args[]) {
int grid[][] = {
{1,1,0,0,0},{1,1,0,0,0},{0,0,0,1,1},{0,0,0,1,1}};
System.out.println(new MaxArea().maxAreaOfIsland(grid));
}
}
还没有评论,来说两句吧...