图论岛屿问题DFS+BFS

leetcode 200 岛屿问题

csharp 复制代码
class Solution {
    //定义对应的方向
    boolean [][] visited;
    int dir[][]={
            {0,1},{1,0},{-1,0},{0,-1}
    };

    public int numIslands(char[][] grid) {
       //对应的二维数组
    int count=0;
    visited=new boolean[grid.length][grid[0].length];

        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (visited[i][j] == false && grid[i][j]=='1') {
                    count++;
                    dfs(grid,i,j);
                }
            }
        }
        return count;
    }

    public  void dfs(char[][]grid,int x,int y)
    {
        if (visited[x][y]==true||grid[x][y]=='0'){
            return;
        }
        visited[x][y]=true;

        for (int i = 0; i <4; i++) {
            int nextX=x+dir[i][0];
            int nextY=y+dir[i][1];
            if (nextY<0||nextX<0||nextX>=grid.length||nextY>=grid[0].length){
                continue;
            }
            dfs(grid,nextX,nextY);
        }

    }
}

BFS代码

csharp 复制代码
class  Solution{
    boolean[][] visited;
    int move[][]={
            {0,1},{0,-1},{1,0},{-1,0}};
    public int numIslands(char[][] grid) {
        int res=0;
        visited=new boolean[grid.length][grid[0].length];
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (!visited[i][j]&&grid[i][j]=='1'){
                    bfs(grid,i,j);
                    res++;
                }
            }
        }
        return  res;
    }
    public  void bfs(char [][] grid,int x,int y){
        Deque<int[]> queue=new ArrayDeque<>(); //创建一个队列
        queue.offer(new int[]{x,y});
        visited[x][y]=true;
        while (!queue.isEmpty()){
            int []cur=queue.poll();
            int m=cur[0];
            int n=cur[1];
            for (int i=0;i<4;i++){
                int nextx=m+move[i][0];
                int nexty=n+move[i][1];
                if (nextx<0||nextx==grid.length||nexty<0||nexty==grid[0].length){
                  continue;
                }
                if (!visited[nextx][nexty]&&grid[nextx][nexty]=='1'){
                    queue.offer(new int[]{nextx,nexty});
                    visited[nextx][nexty]=true;
                }
            }
        }
    }
相关推荐
罗湖老棍子1 天前
【模板】并查集(洛谷P3367)
算法·图论·并查集
wanderist.1 天前
C++输入输出的一些问题
开发语言·c++·图论
Q741_1471 天前
C++ 队列 宽度优先搜索 BFS 力扣 429. N 叉树的层序遍历 每日一题
c++·算法·leetcode·bfs·宽度优先
Snow_day.2 天前
有关排列排列组合(1)
数据结构·算法·贪心算法·动态规划·图论
初晴や3 天前
【C++】图论:基础理论与实际应用深入解析
c++·算法·图论
源代码•宸3 天前
Leetcode—1123. 最深叶节点的最近公共祖先【中等】
经验分享·算法·leetcode·职场和发展·golang·dfs
源代码•宸3 天前
Leetcode—865. 具有所有最深节点的最小子树【中等】
开发语言·经验分享·后端·算法·leetcode·golang·dfs
Tisfy3 天前
LeetCode 0865.具有所有最深节点的最小子树:深度优先搜索(一次DFS + Python5行)
算法·leetcode·深度优先·dfs·题解
Q741_1473 天前
C++ 队列 宽度优先搜索 BFS 力扣 429. N 叉树的层序遍历 C++ 每日一题
c++·算法·leetcode·bfs·宽度优先
闻缺陷则喜何志丹3 天前
【图论 DFS 换根法】3772. 子图的最大得分|2235
c++·算法·深度优先·力扣·图论·换根法