leetcode 959 斜线分割区域

Share
In a N x N grid composed of 1 x 1 squares, each 1 x 1 square consists of a /, , or blank space. These characters divide the square into contiguous regions.

(Note that backslash characters are escaped, so a \ is represented as “\”.)

Return the number of regions.

Example 1:

Input:
[
" /",
"/ "
]
Output: 2
Explanation: The 2x2 grid is as follows:

Example 2:

Input:
[
" /",
" "
]
Output: 1
Explanation: The 2x2 grid is as follows:

Example 3:

Input:
[
“\/”,
“/\”
]
Output: 4
Explanation: (Recall that because \ characters are escaped, “\/” refers to /, and “/\” refers to /.)
The 2x2 grid is as follows:

Example 4:

Input:
[
“/\”,
“\/”
]
Output: 5
Explanation: (Recall that because \ characters are escaped, “/\” refers to /, and “\/” refers to /.)
The 2x2 grid is as follows:

Example 5:

Input:
[
“//”,
"/ "
]
Output: 3
Explanation: The 2x2 grid is as follows:

Note:

1 <= grid.length == grid[0].length <= 30
grid[i][j] is either ‘/’, ‘’, or ’ ’
题解:
我没有用深度优先搜索的方法,我是使用并查集来做的,对于每一个小方块,我将它划分为4个区域,以2*2的网格为例
黄色的线代表了连接
黄色的线是代表连接上了,对于grid的每一个值的取值范围为’’,’/’,’ ‘,当这个值为’/‘或者’ ‘时,我们就将0和1连接起来,2和3连接起来,如果是’‘或者’ '时,就将0和2连接起来,1和3连接起来,处理完这个小方格之后,还要让这个小方格和其它小方格连接起来,最后只需要统计有多少个树根即可
下面贴代码:
class DSU:
def init(self, N):
self.p = range(N)

def find(self, x):
    if self.p[x] != x:
        self.p[x] = self.find(self.p[x])
    return self.p[x]

def union(self, x, y):
    xr = self.find(x)
    yr = self.find(y)
    self.p[xr] = yr

class Solution(object):
def regionsBySlashes(self, grid):
N = len(grid)
dsu = DSU(4 * N * N)
for r, row in enumerate(grid):
for c, val in enumerate(row):
root = 4 * (r*N + c)
if val in '/ ':
dsu.union(root + 0, root + 1)
dsu.union(root + 2, root + 3)
if val in '\ ':
dsu.union(root + 0, root + 2)
dsu.union(root + 1, root + 3)

            # north/south
            if r+1 < N: dsu.union(root + 3, (root+4*N) + 0)
            if r-1 >= 0: dsu.union(root + 0, (root-4*N) + 3)
            # east/west
            if c+1 < N: dsu.union(root + 2, (root+4) + 1)
            if c-1 >= 0: dsu.union(root + 1, (root-4) + 2)

    return sum(dsu.find(x) == x for x in xrange(4*N*N))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值