In 2D binary matrix find the number of islands

前端 未结 2 1526
闹比i
闹比i 2020-12-21 02:29

I am trying to count the number of islands (a group of connected 1s forms an island) in a 2D binary matrix.

Example:

[
[1, 1, 0, 0, 0],
[0, 1, 0, 0,          


        
2条回答
  •  天涯浪人
    2020-12-21 02:47

    Your algorithm is almost correct except for the line 21:

    if r != i and c != j:
        cnt += count_houses(mat, visited, r, c)
    

    Instead you want to use or as you want to continue counting provided at least one of the coordinate is not the same as your center.

    if r != i or c != j:
        cnt += count_houses(mat, visited, r, c)
    

    An alternate and more intuitive way to write this would be the following

    if (r, c) != (i, j):
        cnt += count_houses(mat, visited, r, c)
    

提交回复
热议问题