我必须检查 ■ 是否连续:
_|_ _|_1_|_2_|_3_|_
_|_1_|_■_|_■_|_ _|_
_|_2_|_ _|_ _|_■_|_
_|_3_|_ _|_■_|_ _|_
_|_4_|_■_|_■_|_ _|_
在这种情况下返回 True
例如,如果发生这样的事情:
_|_ _|_1_|_2_|_3_|_
_|_1_|_■_|_■_|_ _|_
_|_2_|_ _|_ _|_■_|_
_|_3_|_ _|_ _|_ _|_
_|_4_|_■_|_■_|_ _|_
在这种情况下返回 False
我正在使用如下列表:
my_list=[[" "," "," "],[" "," "," "],[" "," "," "],
[" "," "," "]]
数字仅在打印电路板时出现,因此我可以使用 my_list 进行任何其他操作。
最佳答案
遍历图表,如果您访问每个节点,那么您就已连接(连续),例如:
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
只要空白图 block 是假的,那么它就应该按原样工作,例如[[1, 1, 0], [0, 0, 1], [0, 1, 0], [1, 1, 0]]
也会返回 True
。如果您对空白图 block 有不同的定义,则只需更改 items
定义中的 if f
。
关于python - 如何检查列表的元素是否连续,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29426303/