岛的个数问题

岛的个数问题,第1张

岛的个数问题



func countIsLand(m [][]int) int {
	if m == nil || m[0] == nil {
		return 0
	}
	N := len(m)
	M := len(m[0])
	res := 0
	for i := 0; i < N; i++ {
		for j := 0; j < M; j++ {
		   if m[i][j] == 1 {
			   res++
			   infect(m,i,j,N,M)
		   }
		}
	}
	return res
}

func infect(m [][]int, i, j, N, M int)  {
	if i < 0 || i >= N || j < 0 || j >= M || m[i][j] != 1 {
		return
	}
	m[i][j] = 2
	infect(m,i+1,j, N,M)
	infect(m,i-1,j, N,M)
	infect(m,i,j+1, N,M)
	infect(m,i,j-1, N,M)
}

func TestCountIsLand(t *testing.T)  { // O(N*M)
	mp := [][]int{
		{1,1,1,1,0,0,1,1,1,1},
		{1,1,1,0,1,0,1,1,1,0},
		{0,1,1,1,1,0,1,1,0,1},
		{0,0,0,0,0,1,0,0,1,1},
		{1,0,0,1,1,0,1,0,1,1},
		{1,0,1,1,0,0,1,1,1,1},
	}
	t.Log(countIsLand(mp))
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5665881.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存