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

修复Lego积木定位函数中同色不同类型积木的识别问题

修复getNeighbour函数的积木定位问题

问题核心

原函数定位brick(砖块)时,仅通过颜色+z值筛选候选位置,误将同色同z但孤立的cube(立方体)位置识别为brick的起始位置(pos1)。结合题目中“同色同z的积木不会相邻”的规则,brick的位置必然是连续相邻的集群,而cube是孤立的单个位置,利用这一特性即可修复错误。

修复方案

  1. 新增相邻位置判断函数,区分连续的brick集群与孤立的cube;
  2. 针对brick类型,通过广度优先搜索(BFS)筛选出所有连续相邻的同色同z位置,自动排除孤立的cube位置。

完整代码实现

def is_adjacent(pos1, pos2):
    # 从`p_xx_yy`格式中提取x、y坐标值
    x1, y1 = map(int, pos1.split('_')[1:])
    x2, y2 = map(int, pos2.split('_')[1:])
    # 判断是否为上下/左右相邻
    return (abs(x1 - x2) == 1 and y1 == y2) or (abs(y1 - y2) == 1 and x1 == x2)

def getNeighbour(target_type, color, z, myDict):
    # 第一步:筛选所有同色同z的候选位置
    candidates = [pos for pos, val in myDict.items() if val[0] == color and val[1] == z]
    if not candidates:
        return None

    if target_type == 'c':
        # cube是单个孤立位置,直接返回(同色同z不相邻,候选列表仅一个元素)
        return candidates[0]
    elif target_type == 'b':
        # 第二步:通过BFS找出所有连续相邻的brick位置集群
        brick_cluster = set()
        queue = [candidates[0]]
        brick_cluster.add(candidates[0])

        while queue:
            current_pos = queue.pop(0)
            for pos in candidates:
                if pos not in brick_cluster and is_adjacent(current_pos, pos):
                    brick_cluster.add(pos)
                    queue.append(pos)
        
        # 返回brick集群的任意一个位置(此处取第一个元素作为pos1)
        return next(iter(brick_cluster))

修复逻辑说明

  • 相邻判断:is_adjacent函数解析位置的x、y坐标,确保仅将上下/左右相邻的位置归为同一brick集群;
  • brick集群筛选:BFS从第一个候选位置出发,遍历所有同色同z的位置,仅将相邻位置加入集群——由于cube和brick同色同z但不相邻,cube的位置会被自动排除;
  • cube定位:同色同z的cube不会相邻,候选列表仅含一个位置,直接返回即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 10:30:54