zoukankan      html  css  js  c++  java
  • leetcode--200. Number of Islands

    Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

    Example 1:

    Input:
    11110
    11010
    11000
    00000
    
    Output: 1
    

    Example 2:

    Input:
    11000
    11000
    00100
    00011
    
    Output: 3

    大神的代码,比较好。将遍历到的点全部变成0,这样就不用visit数组了来记录是否访问过了
    public class Solution {
    
    private int n;
    private int m;
    
    public int numIslands(char[][] grid) {
        int count = 0;
        n = grid.length;
        if (n == 0) return 0;
        m = grid[0].length;
        for (int i = 0; i < n; i++){
            for (int j = 0; j < m; j++)
                if (grid[i][j] == '1') {
                    DFSMarking(grid, i, j);
                    ++count;
                }
        }    
        return count;
    }
    
    private void DFSMarking(char[][] grid, int i, int j) {
        if (i < 0 || j < 0 || i >= n || j >= m || grid[i][j] != '1') return;
        grid[i][j] = '0';
        DFSMarking(grid, i + 1, j);
        DFSMarking(grid, i - 1, j);
        DFSMarking(grid, i, j + 1);
        DFSMarking(grid, i, j - 1);
    }
    }



    我的代码,略微麻烦
    class Solution {
        int[][] visit;
        int ans=0;
        public int numIslands(char[][] grid) {
            if(grid.length==0)
                return 0;
            visit=new int[grid.length][grid[0].length];
            for(int i=0;i<grid.length;i++){
                for(int j=0;j<grid[0].length;j++){
                    if(grid[i][j]=='1'&&visit[i][j]!=1){
                        ans++;
                        fight(i,j,grid);
                    }
                }
            }
            return ans;
        }
        public void fight(int i,int j,char[][] grid){
            visit[i][j]=1;
            if(grid[i][j]=='0')
                return;
            else{
                if(i+1<grid.length&&visit[i+1][j]!=1)
                    fight(i+1,j,grid);
                if(i-1>=0&&visit[i-1][j]!=1)
                    fight(i-1,j,grid);
                if(j+1<grid[0].length&&visit[i][j+1]!=1)
                    fight(i,j+1,grid);
                if(j-1>=0&&visit[i][j-1]!=1)
                    fight(i,j-1,grid);
            }
        }
    }
  • 相关阅读:
    【C++和C#的区别杂谈】后自增运算符的结算时机
    个人作业——软件工程实践总结&个人技术博客
    Unity常见的三种数据本地持久化方案
    C++的逗号运算符
    米哈游--2020春招实习
    厦门飞鱼科技--2020春招实习
    tap4fun(成都尼必鲁)--2020春招实习
    腾讯IEG--2020春招实习
    吉比特&雷霆游戏--2020春招实习
    Docker 基础知识
  • 原文地址:https://www.cnblogs.com/albert67/p/10419748.html
Copyright © 2011-2022 走看看