695. Max Area of Island

来源:互联网 发布:淘宝上比较好的手办店 编辑:程序博客网 时间:2024/06/05 20:52
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.

第一次刷Leetcode,感觉好高大上,,,代码就一个类,,完成题目要求的function就ok,不用自己写main函数,先拿这道水题试手
class Solution {public:    int vis[100][100];    int maxAreaOfIsland(vector<vector<int>>& grid) {              memset(vis, 0, sizeof(vis));        int ans = 0;        for(int i = 0; i < grid.size(); i++)        {            for(int j = 0; j < grid[i].size(); j++)            {                if(grid[i][j] && !vis[i][j])                {                    ans = max(ans, BFS(grid, i, j));                }            }        }        return ans;    }    int xx[4] = {1, -1, 0, 0};    int yy[4] = {0, 0, 1, -1};    int BFS(vector<vector<int>>& grid, int x, int y){        queue<pair<int, int>> q;        q.push(make_pair(x, y));        vis[x][y] = 1;        int cnt = 1;        while(!q.empty())        {            pair<int, int> p = q.front();            q.pop();            for(int i = 0; i < 4; i++)            {                int x = p.first + xx[i];                int y = p.second + yy[i];                if(x >= 0 && x < grid.size() && y >= 0 && y < grid[x].size() && grid[x][y] && !vis[x][y])                {                    cnt++;                    q.push(make_pair(x, y));                    vis[x][y] = 1;                }            }        }        return cnt;    }};


原创粉丝点击