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)BFS
classSolution{publicintmaxAreaOfIsland(int[][] grid){if(grid==null || grid.length==0|| grid[0]==null || grid[0].length==0){return0;}int n = grid.length, m = grid[0].length;// 记录已访问过的坐标boolean[][] flag =newboolean[n][m];// 最终结果, 初始值为0int max=0;//遍历矩阵for(int i=0; i<n; i++){for(int j=0; j<m; j++){//如果当前位置是0或者当前位置访问过, 则进入下一轮循环if(grid[i][j]==0|| flag[i][j]==true){continue;}//当前位置是1, 并且没有访问过, 从这里开始向四周扩散, 返回扩散的最大面积int cur =bfs(grid, flag, i, j);
max = Math.max(max, cur);}}return max;}// 用来表示上下左右四个移动方向privateint[][] moves ={{-1,0},{1,0},{0,-1},{0,1}};// 使用bfs进行扩散, 并返回扩散结束后占据的面积privateintbfs(int[][] grid,boolean[][] flag,int i,int j){int n = grid.length, m = grid[0].length;// 扩散面积初始值是1, 因为grid[i][j]==1int res =1;// 辅助bfs的队列
LinkedList<int[]> queue =newLinkedList<>();
queue.add(newint[]{i,j});
flag[i][j]=true;// bfs主体循环while(!queue.isEmpty()){int[] cur = queue.poll();// 当前位置进行上下左右移动for(int[] move : moves){int x = cur[0]+move[0];int y = cur[1]+move[1];// 如果移动后的坐标不越界并且移动后的坐标对应的值为1, 同时还没有访问过, 说明该位置有效if(x>=0&& x<n && y>=0&& y<m && grid[x][y]==1&& flag[x][y]==false){
queue.add(newint[]{x, y});
flag[x][y]=true;//扩散面积加1
res++;}}}return res;}}
welcome to my blogLeetCode 695. Max Area of Island (Java版; Medium)题目描述Given a non-empty 2D array grid of 0's and 1's, an island is a group of 1's (representing land) connected4-directionally (hori...