图论岛屿问题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;
                }
            }
        }
    }
相关推荐
Cando学算法6 小时前
欧拉回路(一笔画)
数据结构·c++·图论
浅念-1 天前
LeetCode最短路必看:BFS算法原理+经典题解
数据结构·c++·算法·leetcode·职场和发展·bfs·宽度优先
浅念-2 天前
刷穿LeetCode:BFS 解决 Flood Fill 算法
数据结构·c++·算法·leetcode·职场和发展·bfs·宽度优先
多喝开水少熬夜2 天前
dfs思路回溯
算法·深度优先·dfs
xvhao20134 天前
单源、多源最短路
数据结构·c++·算法·深度优先·动态规划·图论·图搜索算法
hnjzsyjyj4 天前
洛谷 P1443:马的遍历 ← BFS
数据结构·bfs
hnjzsyjyj4 天前
洛谷 P1746:离开中山路 ← BFS
bfs
hnjzsyjyj5 天前
洛谷B3862:图的遍历(简单版)← 邻接表
dfs·邻接表
txzrxz5 天前
关于前缀和
算法·动态规划·图论
handler016 天前
算法:图的基本概念
c语言·开发语言·c++·笔记·算法·图论