岛屿数量

题目

给你一个由 '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

posted @ 2020-12-03 10:06  small_lei_it  阅读(112)  评论(0编辑  收藏  举报