463. 岛屿的周长(leetcode)
https://leetcode.cn/problems/island-perimeter/description/
思路:遍历岛屿,一旦遍历到边界或者水则周长++
class Solution {
int res;
boolean[][] vis;
int[][] grid;
int[] dx=new int[]{0,1,0,-1};
int[] dy=new int[]{1,0,-1,0};
int n;
int m;
public int islandPerimeter(int[][] grid) {
n=grid.length;
m=grid[0].length;
this.grid=grid;
vis=new boolean[n][m];
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
{
if(grid[i][j]==1)
{
dfs(i,j);
return res;
}
}
return 0;
}
void dfs(int x,int y)
{
vis[x][y]=true;
for(int i=0;i<4;i++)
{
int a=x+dx[i],b=y+dy[i];
if(a<0 || b<0 || a>=n || b>=m || grid[a][b]==0)
{
// 遍历到边界或者水都是 周长++
res++;
continue;
}
if(a>=0 && b>=0 && a<n && b<m && vis[a][b]==false && grid[a][b]==1)
{
dfs(a,b);
}
}
}
}
分类:
算法 / leetcode
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
2022-10-07 剑指 Offer 03. 数组中重复的数字
2022-10-07 HDFS上传文件