#!/usr/bin/python3 # checks to see if all the labeled regions are connected import sys class node: def __init__(self,id): self.label = 0 self.nbr = [] self.visited = False # count cells in a connected component, see if that matches the count # recorded for that block def compcount(v,c): count = dfs(v) if count != c: print(f'Block {graph[v].label} not connected') sys.exit(43) # depth first search a connected region def dfs(v): count = 1 graph[v].visited = True for i in graph[v].nbr: if graph[i].visited: continue count += dfs(i) return count # input everything (rows,cols) = map(int,sys.stdin.readline().split()) grid=[] for i in range(rows): grid.append(list(map(int,sys.stdin.readline().split()))) # maps each region to a cell count and a starting cell: d = {} # build a graph; edges between cells that have the same label: graph = [node(i) for i in range(rows*cols)] for r in range(rows): for c in range(cols): g1 = r*cols+c graph[g1].label = grid[r][c] if r-1 >= 0 and grid[r][c] == grid[r-1][c]: g2 = (r-1)*cols+c graph[g1].nbr.append(g2) graph[g2].nbr.append(g1) if c-1 >= 0 and grid[r][c] == grid[r][c-1]: g2 = r*cols+c-1 graph[g1].nbr.append(g2) graph[g2].nbr.append(g1) # have we seen this label before? cell = d.get(grid[r][c],None) if cell == None: # new label; save cell location and set count = 1 d[grid[r][c]] = [r,c,1] else: # already seen this label; just update the count cell[2] += 1 # Now check each labeled region to make sure it's connected: for k in d: [r,c,count] = d[k] compcount(r*cols+c,count) sys.exit(42)