标签:for grid int from uri 区域 append http reg
https://leetcode.com/problems/regions-cut-by-slashes/
BFS搜索能连成一片的区域。
class Solution:
def regionsBySlashes(self, grid):
"""
:type grid: List[str]
:rtype: int
"""
from collections import deque
N = len(grid)
G = dict()
# (r, c, d): row, col, direction
count = 0
DIR = "UDLR" # 上下左右
# 边界
for r in [-1, N]:
for c in range(-1, N + 1):
for d in DIR:
G[(r, c, d)] = count
for c in [-1, N]:
for r in range(-1, N + 1):
for d in DIR:
G[(r, c, d)] = count
D = {
("U", " "): [(-1, 0, "D"), (0, 0, "L"), (0, 0, "R")],
("U", "/"): [(-1, 0, "D"), (0, 0, "L")],
("U", "\\"): [(-1, 0, "D"), (0, 0, "R")],
("D", " "): [(1, 0, "U"), (0, 0, "L"), (0, 0, "R")],
("D", "/"): [(1, 0, "U"), (0, 0, "R")],
("D", "\\"): [(1, 0, "U"), (0, 0, "L")],
("L", " "): [(0, -1, "R"), (0, 0, "U"), (0, 0, "D")],
("L", "/"): [(0, -1, "R"), (0, 0, "U")],
("L", "\\"): [(0, -1, "R"), (0, 0, "D")],
("R", " "): [(0, 1, "L"), (0, 0, "U"), (0, 0, "D")],
("R", "/"): [(0, 1, "L"), (0, 0, "D")],
("R", "\\"): [(0, 1, "L"), (0, 0, "U")],
}
def handle(p, s):
r, c, d = p
for dr, dc, dd in D[(d, s)]:
yield (r + dr, c + dc, dd)
for r in range(N):
for c in range(N):
for d in DIR:
p = (r, c, d)
if p in G:
continue # 已访问
count += 1
Q = deque([p])
while Q:
e = Q.popleft()
if e in G:
continue
r1, c1, d1 = e
G[e] = count
for neighbor in handle(e, grid[r1][c1]):
Q.append(neighbor)
return count
Runtime: 236 ms, faster than 76.69% of Python3 online submissions for Regions Cut By Slashes.
标签:for grid int from uri 区域 append http reg
原文地址:https://www.cnblogs.com/lzyerste/p/10163908.html