卡码网KamaCoder 106. 岛屿的周长

题目来源:106. 岛屿的周长

C++题解1:遍历一遍,找每个单元格的临水周长。

cpp 复制代码
#include <iostream>
#include <vector>

using namespace std;

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];
        }
    }
    
    int res = 0;
    for(int i = 0; i < N; i++) {  // 中间
        for(int j = 0; j < M; j++) {
            if(grid[i][j] == 1){
                if(i == 0) res = res+1;
                else if(grid[i-1][j] == 0) res++;
                if(i == N-1) res++;
                else if(grid[i+1][j] == 0) res++;
                if(j == 0) res++;
                else if(grid[i][j-1] == 0) res++;
                if(j == M-1) res++;
                else if(grid[i][j+1] == 0) res++;
            }
        }
    }
    
    cout<<res;
    return 0;
}

C++题解2(来源代码随想录):计算岛屿单元个数,有4个边,每两两相邻的消掉2个边。

那么只需要在计算出相邻岛屿的数量就可以了,相邻岛屿数量为cover。

结果 result = 岛屿数量 * 4 - cover * 2。

cpp 复制代码
#include <iostream>
#include <vector>
using namespace std;
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];
        }
    }
    int sum = 0;    // 陆地数量
    int cover = 0;  // 相邻数量
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            if (grid[i][j] == 1) {
                sum++; // 统计总的陆地数量
                // 统计上边相邻陆地
                if(i - 1 >= 0 && grid[i - 1][j] == 1) cover++;
                // 统计左边相邻陆地
                if(j - 1 >= 0 && grid[i][j - 1] == 1) cover++;
                // 为什么没统计下边和右边? 因为避免重复计算
            }
        }
    }

    cout << sum * 4 - cover * 2 << endl;

}
相关推荐
吃着火锅x唱着歌1 分钟前
LeetCode 3623.统计梯形的数目 I
算法·leetcode·职场和发展
纵有疾風起4 分钟前
【C++—STL】红黑树底层封装与set/map模拟实现
开发语言·c++·经验分享·面试·开源·stl
却道天凉_好个秋10 分钟前
c++ shared_ptr与unique_ptr总结
c++
吃着火锅x唱着歌14 分钟前
LeetCode 2364.统计坏数对的数目
数据结构·算法·leetcode
qq_3363139318 分钟前
java基础-set类集合进阶
java·算法
不知所云,24 分钟前
4. vscode c++ 环境及工程搭建 clangd + mingw
c++·ide·vscode·开发环境·clangd
kyle~27 分钟前
数据结构---堆(Heap)
服务器·开发语言·数据结构·c++
apocelipes27 分钟前
Linux的binfmt_misc机制
linux·c语言·c++·python·golang·linux编程·开发工具和环境
嵌入式老牛28 分钟前
第13章 图像处理之Harris角点检测算法(二)
图像处理·opencv·算法·计算机视觉
渡我白衣29 分钟前
哈希的暴力美学——std::unordered_map 的底层风暴、扩容黑盒与哈希冲突终极博弈
java·c语言·c++·人工智能·深度学习·算法·哈希算法