algorithm - 基于与某个单元格的接近度循环遍历 NxN 个网格单元格
问题描述
我有一个N
按N
网格。我有一个标有0
:
我打算按0
以下顺序循环网格单元格,从单元格开始:
- 从标记的单元格开始
0
- 下一个单元格被标记
1
- 下一个单元格被标记
2
- ...
- 直到到达网格边界
我怎样才能组成循环?
我试图关注这篇文章。但我无法调整它以适应我的情况。
解决方案
您可以使用广度优先搜索填充整个网格:从值为 0 的单元格开始,它将以同心波扩展,向远离中心的每个后续层添加一个。
这是一个例子Python3
from collections import deque
from typing import List, Tuple
class Grid:
"""represents a grid of cells indexed like a matrix:
rows first, then columns
rows, cols, r, c, row, col, cr, cc are ints
rowcol = tuple of ints
"""
eight_offsets = [(1, 1), (1, 0), (1, -1), (0, 1), (0, -1), (-1, 1), (-1, 0), (-1, -1)]
def __init__(self, rows: int, cols: int):
self.rows = rows
self.cols = cols
self.cells = [[None for col in range(cols)] for row in range(rows)]
def fill_grid_BFS(self, rowcol: Tuple[int, int]) -> None:
"""fills each cell with its distance from the cell at rowcol which is zero
"""
row, col = rowcol
self.cells[row][col] = 0
queue = deque([rowcol])
visited = set()
while queue:
current = queue.popleft()
cr, cc = current
rank = self.cells[cr][cc] + 1
visited.add(current)
for neigh in self.get_eight_neighbors(current):
if neigh in visited:
continue
r, c = neigh
self.cells[r][c] = rank
queue.append(neigh)
print(self)
def get_eight_neighbors(self, rowcol: Tuple[int, int]) -> List[Tuple[int, int]]:
"""returns the valid Moore's neighbors that have not been assigned a value yet
"""
row, col = rowcol
neighbors = []
for dr, dc in Grid.eight_offsets:
r, c = row + dr, col + dc
try:
if self.cells[r][c] is None:
neighbors.append((r, c))
except IndexError:
pass
return neighbors
def __str__(self) -> str:
res = []
for row in self.cells:
res.append(' '.join(str(elt) for elt in row))
res.append('\n')
return ''.join(res)
g = Grid(8, 8)
g.fill_grid_BFS((5, 5))
输出:
5 5 5 5 5 5 5 5
5 4 4 4 4 4 4 4
5 4 3 3 3 3 3 3
5 4 3 2 2 2 2 2
5 4 3 2 1 1 1 2
5 4 3 2 1 0 1 2
5 4 3 2 1 1 1 2
5 4 3 2 2 2 2 2
推荐阅读
- python - C:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\BuildTools\\VC\\Tools\\MSVC\\14.29.30133\\bin\\HostX86\\x86\\cl.exe' 失败退出状态为 2
- flutter - 添加折线“子目的地”谷歌地图颤动,针对单个 API 调用进行优化
- javascript - “SyntaxError:无法在模块外使用导入语句”导入模块时导入模块以在 Jest 中产生副作用
- c - 如何在 Squid 的源代码中添加一些 WinAPI 函数并在 Windows 中通过 Cygwin 构建它?
- java - 如何解决 JPA @PersistenceContext 空指针异常
- policy - Rego - 将数组分配给现有数组
- azure-devops - 可以通过管道检索和保留密钥库机密吗?
- html - 带有上传音乐播放列表视图的“添加文件”选项
- mongodb - 控制台中的“[Function:Errorctor]”错误
- amazon-dynamodb - DynamoDB 复合键与简单键性能