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)) }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)