美文网首页LeetCode蹂躏集
LeetCode 695. Max Area of Island

LeetCode 695. Max Area of Island

作者: alexsssu | 来源:发表于2018-01-24 21:01 被阅读0次

    1、BFS

    class Solution {
    public:
        int maxAreaOfIsland(vector<vector<int>>& grid) {
            int maxArea = 0, rows = grid.size(), columns = grid[0].size();
            for (int i = 0; i < rows; ++i) {
                for (int j = 0; j < columns; ++j) {
                    if (grid[i][j] == 1) {
                        maxArea = max(maxArea,BFS(grid, i, j));
                    }
                }
            }
            return maxArea;
        }
    private:
        int BFS(vector<vector<int>>& grid, int row, int column){
            int rows = grid.size(), columns = grid[0].size(), ans = 1;
            queue<pair<int, int>> q;
            q.push({row,column});
            grid[row][column] = 2;
            vector<int> dir({0,1,0,-1,0});
            while (!q.empty()) {
                int r = q.front().first;
                int c = q.front().second;
                q.pop();
                for (int i = 0; i < 4; ++i) {
                    int rr = r + dir[i];
                    int cc = c + dir[i+1];
                    if (0 <= rr && rr < rows && 0 <= cc && cc < columns && grid[rr][cc] == 1) {
                        ++ans;
                        q.push({rr,cc});
                        grid[rr][cc] = 2;
                    }
                }
            }
            return ans;
        }
    };
    

    相关文章

      网友评论

        本文标题:LeetCode 695. Max Area of Island

        本文链接:https://www.haomeiwen.com/subject/qxrpaxtx.html