图论岛屿问题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;
                }
            }
        }
    }
相关推荐
Flower#17 小时前
【模板】图论 最短路 (Floyd+SPFA+Dijkstra)
c++·图论
Tisfy18 小时前
LeetCode 2209.用地毯覆盖后的最少白色砖块:记忆化搜索之——深度优先搜索(DFS)
算法·leetcode·深度优先·dfs·题解·记忆化搜索·深度优先搜索
JNU freshman1 天前
图论 之 弗洛伊德算法求解全源最短路径
算法·图论
mvufi1 天前
day56 第十一章:图论part06
c++·算法·图论
分别努力读书1 天前
acm培训 part 7
算法·图论
银河梦想家2 天前
【Day44 LeetCode】图论问题 Ⅱ
算法·leetcode·图论
Coco_92642 天前
Hot100 图论
图论
JNU freshman2 天前
图论 之 DFS
算法·深度优先·图论
Ritsu栗子2 天前
代码随想录算法训练day60---图论系列5《并查集》
c++·算法·图论
柯宝最帅3 天前
图论(四):图的中心性——度中心性&介数中心性&紧密中心性
图论