695. Max Area of Island
来源:互联网 发布:安卓锁屏软件 编辑:程序博客网 时间:2024/06/12 08:17
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.
class Solution { public int maxAreaOfIsland(int[][] grid) { if (grid.length == 0 || grid[0].length == 0)return 0;int m = grid.length; // 高int n = grid[0].length; // 宽boolean[][] flag = new boolean[m][n]; // 判定是否来到过这个点int re = 0; // 返回值for (int i = 0; i < m; ++i) { // 遍历整个grid数组for (int j = 0; j < n; ++j) {if (flag[i][j])continue;elseflag[i][j] = true;if (grid[i][j] == 1) {int cur = 0;LinkedList<int[]> dfs = new LinkedList<>();dfs.addFirst(new int[] { i, j });while (!dfs.isEmpty()) {int[] curPos = dfs.poll();int ii = curPos[0];int jj = curPos[1];cur += 1;if (ii - 1 >= 0 && !flag[ii - 1][jj] && grid[ii - 1][jj] == 1) {dfs.addFirst(new int[] { ii - 1, jj });flag[ii - 1][jj] = true;}if (ii + 1 < m && !flag[ii + 1][jj] && grid[ii + 1][jj] == 1) {dfs.addFirst(new int[] { ii + 1, jj });flag[ii + 1][jj] = true;}if (jj - 1 >= 0 && !flag[ii][jj - 1] && grid[ii][jj - 1] == 1) {dfs.addFirst(new int[] { ii, jj - 1 });flag[ii][jj - 1] = true;}if (jj + 1 < n && !flag[ii][jj + 1] && grid[ii][jj + 1] == 1) {dfs.addFirst(new int[] { ii, jj + 1 });flag[ii][jj + 1] = true;}}re = Math.max(re, cur);}}}return re; }}
阅读全文
0 0
- 695. Max Area of Island
- 695. Max Area of Island
- 695. Max Area of Island
- 695. Max Area of Island
- 695. Max Area of Island
- 695. Max Area of Island
- 695. Max Area of Island
- LWC 53:695. Max Area of Island
- leetcode 695. Max Area of Island 解法
- [LeetCode] Algorithms-695. Max Area of Island
- DFS:695. Max Area of Island
- Leetcode 695. Max Area of Island
- LeetCode-695. Max Area of Island
- 695. Max Area of Island Difficulty: Easy
- LeetCode 695. Max Area of Island
- LeetCode-695. Max Area of Island
- [LeetCode] 695. Max Area of Island
- 【LeetCode】695. Max Area of Island
- 零基础转行学web前端开发好学吗?爱创课堂告诉你
- 电脑蓝屏 各种模式进去之后立马蓝屏 pe状态下无法访问C盘
- 链表问题---打印两个有序链表的公共部分
- JAVA提高篇(39)Socket通信TCP(二)
- 微信公众平台开发授权
- 695. Max Area of Island
- CentOS6.5通过SSH免密码登陆
- 节后无心工作啊
- SpringMVC的各种前后台参数绑定传参方式
- 建造者模式
- PAT 甲级 1103. Integer Factorization (30)
- 插入数据库显示问号问题
- PTA 7-2 列车调度(25 分) 25分代码
- 数据结构:表