doutan5798 2019-08-02 19:29 采纳率: 100%
浏览 70

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

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

  • 写回答

1条回答 默认 最新

  • dounuogong0358 2019-08-03 04:23
    关注

    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())
    
    评论

报告相同问题?

悬赏问题

  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退