You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python对字典关联值分组,生成含组号的新字典

Group Connected Squares into Components Using Python

Looks like you need to identify connected components in your graph of squares and map each square to its corresponding group ID. This is a classic graph traversal problem—we can use either BFS (Breadth-First Search) or DFS (Depth-First Search) to solve it efficiently.

Approach

Here's a step-by-step breakdown of how to do this:

  • Track visited nodes: Use a set to keep track of squares we've already processed so we don't reprocess them.
  • Iterate through each square: For every square that hasn't been visited yet, start a traversal to find all connected squares.
  • Assign group IDs: All squares in the same connected component get the same group number. We increment the group number each time we finish processing a new component.

Solution Code

Let's implement this with BFS (it's great for avoiding recursion depth issues with large graphs):

def map_connected_groups(graph):
    visited = set()
    group_mapping = {}
    current_group = 1
    
    # Iterate over each square in the original dictionary
    for square in graph:
        if square not in visited:
            # Start BFS to find all connected squares in this component
            queue = [square]
            visited.add(square)
            
            while queue:
                current_square = queue.pop(0)
                # Assign the current group number to this square
                group_mapping[current_square] = current_group
                
                # Add all connected neighbors to the queue if not visited
                for neighbor in graph[current_square]:
                    if neighbor not in visited:
                        visited.add(neighbor)
                        queue.append(neighbor)
            
            # Move to the next group for the next component
            current_group += 1
    
    return group_mapping

# Example usage with your provided dictionary
square_graph = {
    1: [4],
    2: [3, 5],
    3: [2, 5],
    4: [1, 6],
    5: [2, 3],
    6: [4, 8],
    7: [9, 10],
    8: [6, 11],
    9: [7, 10],
    10: [7, 9],
    11: [8]
}

# Generate the group mapping
result = map_connected_groups(square_graph)
print(result)

Output

Running this code will give you the following result, where each key is a square number and the value is its group ID:

{1: 1, 4: 1, 6: 1, 8: 1, 11: 1, 2: 2, 3: 2, 5: 2, 7: 3, 9: 3, 10: 3}

Alternative: DFS Implementation

If you prefer using DFS (recursive approach), here's a quick alternative—just note that for very large graphs, you might hit Python's recursion limit:

def map_connected_groups_dfs(graph):
    visited = set()
    group_mapping = {}
    current_group = 1
    
    def dfs(node):
        visited.add(node)
        group_mapping[node] = current_group
        for neighbor in graph[node]:
            if neighbor not in visited:
                dfs(neighbor)
    
    for square in graph:
        if square not in visited:
            dfs(square)
            current_group += 1
    
    return group_mapping

Both approaches will correctly group your connected squares. The BFS method is generally safer for larger datasets, while the DFS approach is more concise.

内容的提问来源于stack exchange,提问作者PolyGeo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:30:51