"""R607:从已运行合成评分格识别四邻连通区域;缺失不是零。""" from collections import deque FAST = [2, 3, 4, 5] SLOW = [10, 12, 14, 16] SCORES = [[6, 7, -2, 1], [7, 8, -1, 2], [-3, -2, None, 1], [1, 0, 2, 25]] def components(scores, threshold=5): good = {(i, j) for i, row in enumerate(scores) for j, score in enumerate(row) if score is not None and score >= threshold} found = [] while good: start = min(good) good.remove(start) queue, region = deque([start]), [start] while queue: i, j = queue.popleft() for candidate in [(i-1, j), (i+1, j), (i, j-1), (i, j+1)]: if candidate in good: good.remove(candidate) queue.append(candidate) region.append(candidate) found.append(sorted(region)) return found def representative(region, scores): return min(region, key=lambda p: ( sum(abs(p[0]-q[0]) + abs(p[1]-q[1]) for q in region), -scores[p[0]][p[1]], p)) def run(): regions = components(SCORES) cells = sum(len(row) for row in SCORES) observed = sum(value is not None for row in SCORES for value in row) acceptable = sum(value is not None and value >= 5 for row in SCORES for value in row) assert sum(map(len, regions)) == acceptable eligible = [region for region in regions if len(region) >= 4] assert [len(region) for region in regions] == [4, 1] assert len(eligible) == 1 point = representative(eligible[0], SCORES) assert point == (1, 1) assert SCORES[3][3] == 25 and (3, 3) not in eligible[0] missing_bridge = components([[6, None, 7]]) assert [len(region) for region in missing_bridge] == [1, 1] print(f"cells={cells} observed={observed} missing={cells-observed} acceptable={acceptable}") print("component_sizes=" + str([len(region) for region in regions])) print(f"selected_fast={FAST[point[0]]} selected_slow={SLOW[point[1]]} score={SCORES[point[0]][point[1]]}") print("isolated_peak=25 rejected; missing_bridge_sizes=[1, 1]") if __name__ == "__main__": run()