KamaCoder 100. 岛屿的最大面积 + Leetcode 695. Max Area of Island

题目描述

给定一个由 1(陆地)和 0(水)组成的矩阵,计算岛屿的最大面积。岛屿面积的计算方式为组成岛屿的陆地的总数。岛屿由水平方向或垂直方向上相邻的陆地连接而成,并且四周都是水域。你可以假设矩阵外均被水包围。

输入描述

第一行包含两个整数 N, M,表示矩阵的行数和列数。后续 N 行,每行包含 M 个数字,数字为 1 或者 0,表示岛屿的单元格。

输出描述

输出一个整数,表示岛屿的最大面积。如果不存在岛屿,则输出 0。

输入示例

思路

之前是统计岛屿的数量,现在是搜索每个岛屿上“1”的数量,然后取一个最大值。

C++深度优先搜索
#include <iostream>
#include <vector>
using namespace std;
int count;
int dir[4][2] = {0, 1, 1, 0, -1, 0, 0, -1};

void dfs(const vector<vector<int>>& grid, vector<vector<bool>>& visited, int x, int y) {
    if (visited[x][y] || grid[x][y] == 0) return;
    visited[x][y] = true;
    count++;
    for (int i = 0; i < 4; ++i) {
        int nextx = x + dir[i][0];
        int nexty = y + dir[i][1];
        if (nextx < 0 || nextx >= grid.size() || nexty < 0 || nexty >= grid[0].size()) continue;
        dfs(grid, visited, nextx, nexty);
    }
}

int main() {
    int n, m;
    cin >> n >> m;
    vector<vector<int>> grid(n, vector<int>(m, 0));
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < m; ++j) {
            cin >> grid[i][j];
        }
    }
    vector<vector<bool>> visited = vector<vector<bool>>(n, vector<bool>(m, false));
    int result = 0;
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < m; ++j) {
            if (!visited[i][j] && grid[i][j] == 1) {
                count = 0;
                dfs(grid, visited, i, j);
                result = max(result, count);
            }
        }
    }
    cout << result << endl;
}

C++广度优先搜索

#include <iostream>
#include <vector>
#include <queue>
using namespace std;
int count;
int dir[4][2] = {0, 1, 1, 0, -1, 0, 0, -1};

void bfs(const vector<vector<int>>& grid, vector<vector<bool>>& visited, int x, int y) {
    queue<pair<int, int>> que;
    que.push({x, y});
    visited[x][y] = true;
    count++;
    while(!que.empty()) {
        pair<int, int> cur = que.front(); que.pop();
        int curx = cur.first;
        int cury = cur.second;
        for (int i = 0; i < 4; ++i) {
            for (int j = 0; j < 4; ++j) {
                int nextx = curx + dir[i][0];
                int nexty = cury + dir[i][1];
                if (nextx < 0 || nextx >= grid.size() || nexty < 0 || nexty >= grid[0].size()) continue;
                if (!visited[nextx][nexty] && grid[nextx][nexty] == 1) {
                    count++;
                    que.push({nextx, nexty});
                    visited[nextx][nexty] = true;
                }
            }
        }
    }
}

int main() {
    int n, m;
    cin >> n >> m;
    vector<vector<int>> grid(n, vector<int>(m, 0));
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < m; ++j) {
            cin >> grid[i][j];
        }
    }
    vector<vector<bool>> visited = vector<vector<bool>>(n, vector<bool>(m, false));
    int result = 0;
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < m; ++j) {
            if (!visited[i][j] && grid[i][j] == 1) {
                count = 0;
                bfs(grid, visited, i, j);
                result = max(result, count);
            }
        }
    }
    cout << result << endl;
}

Python深度优先搜索

dir = [(0, 1), (1, 0), (0, -1), (-1, 0)]

def dfs(grid, visited, x, y):
    global count
    if (visited[x][y] == True or grid[x][y] == 0): return
    visited[x][y] = True
    count += 1
    # print(x, y, count)
    for dx, dy in dir:
        nextx, nexty = x + dx, y + dy
        if nextx < 0 or nextx >= len(grid) or nexty < 0 or nexty >= len(grid[0]):
            continue
        if grid[nextx][nexty] == 1 and not visited[nextx][nexty]:
            dfs(grid, visited, nextx, nexty)
        
def main():
    n, m = map(int, input().split())
    grid = [list(map(int, input().split())) for _ in range(n)]
    visited = [[False] * (m) for _ in range(n)]
    global count
    result = 0
    for i in range(n):
        for j in range(m):
            if (grid[i][j] == 1 and not visited[i][j]):
                count = 0
                dfs(grid, visited, i, j)
                result = max(result, count)
                
    print(result)
    
if __name__ == "__main__":
    main()

Python广度优先搜索

from collections import deque
dir = [(0, 1), (1, 0), (0, -1), (-1, 0)]

def bfs(grid, visited, x, y):
    global count
    que = deque([(x, y)])
    visited[x][y] = True
    count += 1
    while(que):
        curx, cury = que.popleft()
        # print(curx, cury, count)
        for dx, dy in dir:
            nextx, nexty = curx + dx, cury + dy
            if nextx < 0 or nextx >= len(grid) or nexty < 0 or nexty >= len(grid[0]):
                continue
            if grid[nextx][nexty] == 1 and not visited[nextx][nexty]:
                count += 1
                que.append((nextx, nexty))
                visited[nextx][nexty] = True
        
def main():
    n, m = map(int, input().split())
    grid = [list(map(int, input().split())) for _ in range(n)]
    visited = [[False] * (m) for _ in range(n)]
    global count
    result = 0
    for i in range(n):
        for j in range(m):
            if (grid[i][j] == 1 and not visited[i][j]):
                count = 0
                bfs(grid, visited, i, j)
                result = max(result, count)
                
    print(result)
    
if __name__ == "__main__":
    main()

Leetcode 695. Max Area of Island

代码

Python广度优先搜索
from collections import deque
class Solution:
    def bfs(self, grid, visited, x, y):
        dir = [(0, 1), (1, 0), (0, -1), (-1, 0)]
        global count
        que = deque([(x, y)])
        visited[x][y] = True
        count += 1
        while(que):
            curx, cury = que.popleft()
            # print(curx, cury, count)
            for dx, dy in dir:
                nextx, nexty = curx + dx, cury + dy
                if nextx < 0 or nextx >= len(grid) or nexty < 0 or nexty >= len(grid[0]):
                    continue
                if grid[nextx][nexty] == 1 and not visited[nextx][nexty]:
                    count += 1
                    que.append((nextx, nexty))
                    visited[nextx][nexty] = True

    def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
        n, m = len(grid), len(grid[0])
        visited = [[False] * (m) for _ in range(n)]
        global count
        result = 0
        for i in range(n):
            for j in range(m):
                if (grid[i][j] == 1 and not visited[i][j]):
                    count = 0
                    self.bfs(grid, visited, i, j)
                    result = max(result, count)
        return result
C++深度优先搜索
class Solution {
public:
    int count;
    int dir[4][2] = {0, 1, 1, 0, -1, 0, 0, -1};
    void dfs(const vector<vector<int>>& grid, vector<vector<bool>>& visited, int x, int y) {
        if (visited[x][y] || grid[x][y] == 0) return;
        visited[x][y] = true;
        count++;
        for (int i = 0; i < 4; ++i) {
            int nextx = x + dir[i][0];
            int nexty = y + dir[i][1];
            if (nextx < 0 || nextx >= grid.size() || nexty < 0 || nexty >= grid[0].size()) continue;
            dfs(grid, visited, nextx, nexty);
        }
    }
    int maxAreaOfIsland(vector<vector<int>>& grid) {
        int n = grid.size();
        int m = grid[0].size();
        vector<vector<bool>> visited = vector<vector<bool>>(n, vector<bool>(m, false));
        int result = 0;
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < m; ++j) {
                if (!visited[i][j] && grid[i][j] == 1) {
                    count = 0;
                    dfs(grid, visited, i, j);
                    result = max(result, count);
                }
            }
        }
        return result;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值