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;    }}


原创粉丝点击