zoukankan      html  css  js  c++  java
  • 岛屿数量

    题目

    给你一个由 '1'(陆地)和 '0'(水)组成的的二维网格,请你计算网格中岛屿的数量。

    岛屿总是被水包围,并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。

    此外,你可以假设该网格的四条边均被水包围。

    输入:grid = [
      ["1","1","1","1","0"],
      ["1","1","0","1","0"],
      ["1","1","0","0","0"],
      ["0","0","0","0","0"]
    ]
    输出:1
    

    解题思路

    遍历递归

    1. 遍历岛这个二维数组,如果当前数为1,则将岛个数+1并进入“感染函数
    2. “感染函数”其实就是一个递归的过程,因为每座岛由相邻的四座岛形成,所以可以感染周围四座岛。将1的岛感染成2,其目的是避免了遍历过程中的重复计数情况。

    代码

    package main
    
    import "fmt"
    
    func CountIsland(nums [4][4]int) int {
    	rows, col := len(nums), len(nums[0])
    	count := 0
    	for i := 0; i < rows; i ++ {
    		for j := 0; j < col; j ++ {
    			if nums[i][j] == 1 {
    				count++
    				infect(nums, i, j)
    			}
    
    		}
    	}
    
    	return count
    }
    
    func infect(nums [4][4]int, row, col int) {
    	if row < 0 || row >= len(nums) || col < 0 || col >= len(nums) || nums[row][col] != 1 {
    		return
    	}
    
    	nums[row][col] = 2
    
    	infect(nums, row+1 ,col)
    	infect(nums, row-1, col)
    	infect(nums, row, col+1)
    	infect(nums, row, col-1)
    }
    
    
    func main() {
    	nums := [4][4]int{
    		{1,	0,	1,	0},
    		{0,	0,	0,	0},
    		{1,	0,	1,	0},
    		{0,	0,	0,	0},
    	}
    
    	res := CountIsland(nums)
    	fmt.Println(res)
    }
    

      地址:https://mp.weixin.qq.com/s/Caa1G1uAzsnc2KUlfSV4tg

  • 相关阅读:
    给入门程序员的一些学习建议(一定要看)
    拦截器工作原理
    Struts 2中如何解决中文乱码问题?
    struts1与struts2的区别。
    MVC是什么?
    spring MVC工作原理
    C#中,子类构造函数调用父类父类构造函数的正确方式
    泛型的优点
    jsp的page、request、session、application四个作用域的作用
    jsp转发与重定向的区别
  • 原文地址:https://www.cnblogs.com/smallleiit/p/14077980.html
Copyright © 2011-2022 走看看