码迷,mamicode.com
首页 > 其他好文 > 详细

959. Regions Cut By Slashes

时间:2018-12-23 13:56:39      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:for   grid   int   from   uri   区域   append   http   reg   

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

标签:for   grid   int   from   uri   区域   append   http   reg   

原文地址:https://www.cnblogs.com/lzyerste/p/10163908.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!