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);
            }
        }
    }
}

 

posted @   风乐  阅读(13)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
历史上的今天:
2022-10-07 剑指 Offer 03. 数组中重复的数字
2022-10-07 HDFS上传文件
点击右上角即可分享
微信分享提示