如何检查列表的元素是否连续

Guo*_*377 2 python algorithm list

我必须检查■是否是连续的:

_|_ _|_1_|_2_|_3_|_
_|_1_|_?_|_?_|_ _|_
_|_2_|_ _|_ _|_?_|_
_|_3_|_ _|_?_|_ _|_
_|_4_|_?_|_?_|_ _|_
Run Code Online (Sandbox Code Playgroud)

在这种情况下返回True

例如,如果发生类似这样的事情:

_|_ _|_1_|_2_|_3_|_
_|_1_|_?_|_?_|_ _|_
_|_2_|_ _|_ _|_?_|_
_|_3_|_ _|_ _|_ _|_
_|_4_|_?_|_?_|_ _|_
Run Code Online (Sandbox Code Playgroud)

在这种情况下返回False

我正在使用以下列表:

my_list=[[" "," "," "],[" "," "," "],[" "," "," "],
[" "," "," "]]
Run Code Online (Sandbox Code Playgroud)

这些数字仅在打印电路板时出现,因此我使用my_list进行其他操作.

ACh*_*ion 5

走图表,如果你访问每个节点,那么你就连接了(连续),例如:

def is_contiguous(grid):
    items = {(x, y) for x, row in enumerate(grid) for y, f in enumerate(row) if f}
    directions = [(0, 1), (1, 0), (-1, 0), (0, -1), (1, 1), (1, -1), (-1, 1), (-1, -1)]
    neighbours = {(x, y): [(x+dx, y+dy) for dx, dy in directions if (x+dx, y+dy) in items]
                  for x, y in items}

    closed = set()
    fringe = [next(iter(items))]
    while fringe:
        i = fringe.pop()
        if i in closed:
            continue
        closed.add(i)
        for n in neighbours[i]:
            fringe.append(n)

    return items == closed

>>> is_contiguous([["X", "X", ""], ["", "", "X"], ["", "X", ""], ["X", "X", ""]])
True
>>> is_contiguous([["X", "X", ""], ["", "", "X"], ["", "", ""], ["X", "X", ""]])
False
Run Code Online (Sandbox Code Playgroud)

只要空白的瓷砖是假的,那么这应该按原样工作,例如[[1, 1, 0], [0, 0, 1], [0, 1, 0], [1, 1, 0]]也会返回True.如果你有一个空白瓷砖的不同定义,然后就改变if fitems定义.