LeetCode 695. 岛屿的最大面积

主页有其他数据结构内容(持续更新中)

难度:Medium

代码:

法一:dfs

class Solution {
private:
    int count;  //  计数器
    int direction[4][2] = {0, 1, 1, 0, 0, -1, -1, 0};
    void dfs(vector<vector<int>>& grid, vector<vector<bool>>& visited, int x, int y) {
        for(int k = 0; k < 4; k++) {
            int nextX = x + direction[k][0];
            int nextY = y + direction[k][1];
            if(nextX < 0 || nextX >= grid.size() || nextY < 0 || nextY >= grid[0].size()) {
                continue;
            }
            if(!visited[nextX][nextY] && grid[nextX][nextY] == 1) {
                visited[nextX][nextY] = true;
                count++;
                dfs(grid, visited, nextX, nextY);
            }
        }
    }
public:
    int maxAreaOfIsland(vector<vector<int>>& grid) {
        int m = grid.size();
        int n = grid[0].size();
        vector<vector<bool>> visited(m, vector<bool>(n, false));
        int res = 0;
        for(int i = 0; i < m; i++) {
            for(int j = 0; j < n; j++) {
                if(!visited[i][j] && grid[i][j] == 1) {
                    visited[i][j] = true;
                    count = 1;
                    dfs(grid, visited, i, j);
                    res = max(res, count);
                }
            }
        }
        return res;
    }
};

法二:bfs

class Solution {
private:
    int count;  //  计数器
    int direction[4][2] = {0, 1, 1, 0, 0, -1, -1, 0};
    void bfs(vector<vector<int>>& grid, vector<vector<bool>>& visited, int x, int y) {
        queue<pair<int, int>> q;
        q.push({x, y});
        visited[x][y] = true;
        while(!q.empty()) {
            pair<int, int> cur = q.front();
            q.pop();
            for(int k = 0; k < 4; k++) {
                int nextX = cur.first + direction[k][0];
                int nextY = cur.second + direction[k][1];
                if(nextX < 0 || nextX >= grid.size() || nextY < 0 || nextY >= grid[0].size()) {
                    continue;
                }
                if(!visited[nextX][nextY] && grid[nextX][nextY] == 1) {
                    q.push({nextX, nextY});
                    visited[nextX][nextY] = true;
                    count++;
                }
            }
        }
    }
public:
    int maxAreaOfIsland(vector<vector<int>>& grid) {
        int m = grid.size();
        int n = grid[0].size();
        vector<vector<bool>> visited(m, vector<bool>(n, false));
        int res = 0;
        for(int i = 0; i < m; i++) {
            for(int j = 0; j < n; j++) {
                if(!visited[i][j] && grid[i][j] == 1) {
                    count = 1;
                    bfs(grid, visited, i, j);
                    res = max(res, count);
                }
            }
        }
        return res;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值