计算二维数组中的块组总数?

Let's consider you have given a 2D array with values (0 or 1).

Count the total number of group of adjacent 1's in a given array.

Example 1:
1, 0, 0
0, 0, 0
0, 0, 1

Answer: 2

Explanation: In the above example, single 1's block is also considered as one group.


Example 2:
1, 1, 0, 1, 1, 0
0, 1, 0, 0, 0, 1
0, 1, 0, 1, 1, 0
0, 1, 1, 0, 0, 0

Answer: 1

Explanation: In the above example, a group of 1's block is adjacent with at least one 1's block.


My solution: https://play.golang.org/p/nyw4lm6yrQ1

But it looks like, the time complexity is O(n^2)

Examples

Its famous number of island problem. You can perform dfs to solve this problem easily by keeping an boolean matrix of visited cells.

class Graph: 

    def __init__(self, row, col, g): 
        self.ROW = row 
        self.COL = col 
        self.graph = g 

# to check validity of cell
    def isSafe(self, i, j, visited): 
        return (i >= 0 and i < self.ROW and 
                j >= 0 and j < self.COL and 
                not visited[i][j] and self.graph[i][j]) 


    def DFS(self, i, j, visited):

        row = [-1, -1, -1,  0, 0,  1, 1, 1]; 
        col = [-1,  0,  1, -1, 1, -1, 0, 1]; 


        visited[i][j] = True

        # check all 8 neighbours and mark them visited
        # as they will be part of group
        for k in range(8): 
            if self.isSafe(i + row[k], j + col[k], visited): 
                self.DFS(i + row[k], j + col[k], visited) 


    def group(self): 

        visited = [[False for j in range(self.COL)]for i in range(self.ROW)] 

        count = 0
        for i in range(self.ROW): 
            for j in range(self.COL): 
                # traverse not visited cell
                if visited[i][j] == False and self.graph[i][j] == 1: 
                    self.DFS(i, j, visited) 
                    count += 1

        return count

`

g = [[1, 1, 0, 0, 0], 
    [0, 1, 0, 0, 1], 
    [1, 0, 0, 1, 1], 
    [0, 0, 0, 0, 0], 
    [1, 0, 1, 0, 1]]
graphe = graph(len(g),len(g[0]),g)
print(graphe.group())