959. Regions Cut By Slashes
Posted lzyerste
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了959. Regions Cut By Slashes相关的知识,希望对你有一定的参考价值。
https://leetcode.com/problems/regions-cut-by-slashes/
题解1,搜索
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.
以上是关于959. Regions Cut By Slashes的主要内容,如果未能解决你的问题,请参考以下文章
将 dplyr 函数 group_by() 与 cut() 一起使用