当前位置:网站首页>leetcode463. 岛屿的周长(简单)
leetcode463. 岛屿的周长(简单)
2022-06-11 16:01:00 【重you小垃】



法一:遍历每个方格,判断四周的位置,如果是边界外或者是水域则ans++
法二优化:由于只有一个岛屿,所以可以优化到只遍历它周围的格子
class Solution {
public:
int flag[105][105];
int xy[4][2] = {
0, 1, 0, -1, 1, 0, -1, 0};
int dfs(vector<vector<int>>& grid, int x, int y) {
if (!grid[x][y]) return 1;
int n = grid.size(), m = grid[0].size(), ans = 0;
flag[x][y] = 1;
for (int i = 0; i < 4; ++i) {
int xx = x + xy[i][0];
int yy = y + xy[i][1];
if (xx < 0 || xx >= n || yy < 0 || yy >= m) {
ans++;
continue;
}
if (!flag[xx][yy]) ans += dfs(grid, xx, yy);
}
return ans;
}
int islandPerimeter(vector<vector<int>>& grid) {
int n = grid.size(), m = grid[0].size(), ans = 0;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
if (grid[i][j]) {
ans = dfs(grid, i, j);
return ans;
}
}
}
return ans;
}
};
边栏推荐
- MSDN download win11 method, simple and easy to operate
- JDBC debugging error, ask for guidance
- laravel8 实现签到功能案例
- 电脑下面的任务栏怎么显示打开的程序
- How the autorunner automated test tool creates a project -alltesting | Zezhong cloud test
- Nat Common | le Modèle linguistique peut apprendre des distributions moléculaires complexes
- 面试高频算法题---最长回文子串
- Easy to use GS_ Dump and GS_ Dumpall command export data
- Class and__ proto__ Property, the class prototype chain has two inheritance routes
- C# 启动一个外部exe文件,并传入参数
猜你喜欢

Project workspace creation steps - Zezhong ar automated test tool

List和Set存取元素的差异

Nat Commun|语言模型可以学习复杂的分子分布

Deep separable convolution

Talk about data center network again

Customized thread communication (lock) of JUC

3000 words to teach you how to use mot
![Interview classic question: how to do the performance test? [Hangzhou multi surveyors] [Hangzhou multi surveyors \wang Sir]](/img/ea/2c5b48b08a9654b61694b93a2e7d0a.png)
Interview classic question: how to do the performance test? [Hangzhou multi surveyors] [Hangzhou multi surveyors \wang Sir]

Detailed explanation of opengauss multi thread architecture startup process

Step 4 of installation in RF: an error is reported when installing the robotframework-selenium 2library
随机推荐
想学好ArrayList,看完这篇就够了
09-最小生成树 公路村村通
Detailed explanation of opengauss multi thread architecture startup process
Nat commun | language model can learn complex molecular distribution
laravel 8 使用passport 进行Auth验证及颁发token
PyQt5 使QPlainTextEdit控件支持行号显示
one hundred and twenty-three thousand one hundred and twenty-three
Nat Common | le Modèle linguistique peut apprendre des distributions moléculaires complexes
WGet command use
AutoRunner自动化测试工具如何创建项目-Alltesting|泽众云测试
List和Dict数据类型作用详解
Easy to use GS_ Dump and GS_ Dumpall command export data
再聊数据中心网络
Database design recommendations
postgresql创建数据库
How to optimize the performance of compose? Find the answer through "underlying principles" | developers say · dtalk
Nat Commun|语言模型可以学习复杂的分子分布
Dapr mind map
【剑指Offer】22.链表中倒数第K节点
Import data: GS_ restore or MERGE INTO? See which one suits you better