Regions Cut by Slashes
在上周的 leetcode 周竞赛中,我用迭代的方法解决这个题,却超时了。
赛后,我看了别人的方法,思路基本一样。只不过别人用的递归。
开始我还以为是两种实现方式有什么差异。后面分析一下才发现,我在每层访问一个坐标的时候,没有及时把它设置成已访问,导致这个点被重复访问了太多次。
Iteration Solution
code
class Solution(object):
def regionsBySlashes(self, grid):
"""
:type grid: List[str]
:rtype: int
"""
self.count = 0
h = len(grid)
w = h
b = 3
nh, nw = b * h, b * w
dic = {}
table = [[0 for j in range(nw)] for i in range(nh)]
details = [[0 for j in range(nw + 2)] for i in range(nh + 2)]
for i in range(h):
for j in range(w):
if grid[i][j] == ' ':
continue
if grid[i][j] == '/':
for k in range(b):
table[b * i + k][b * j + b - 1 - k] = -1
continue
for k in range(b):
table[b * i + k][b * j + k] = -1
res = 0
for i in range(nh):
for j in range(nw):
if table[i][j] == 0:
res += 1
stack = [[i, j]]
# print 'i, j', i, j
while stack:
ti, tj = stack.pop(0)
# print 'ti, tj:', ti, tj
table[ti][tj] = res
for ni, nj in [[ti - 1, tj], [ti + 1, tj], [ti, tj - 1], [ti, tj + 1]]:
self.count += 1
details[ni + 1][nj + 1] += 1
if (ni, nj) not in dic:
dic[(ni, nj)] = 0
dic[(ni, nj)] += 1
if ni < 0 or ni >= nh or nj < 0 or nj >= nw:
continue
if table[ni][nj] == 0:
table[ni][nj] = res # 如果不在这里加上被访问的记号,那么这一层里会访问这个点多次。
stack.append([ni, nj])
for row in details:
for col in row:
print '\t%d' % col,
print ''
return res
solver = Solution()
solver.regionsBySlashes([" /","/ "])
output
0 1 1 1 1 1 0 0
1 2 3 3 3 1 2 0
1 3 4 4 2 4 1 1
1 3 4 2 4 2 3 1
1 3 2 4 2 4 3 1
1 1 4 2 4 4 3 1
0 2 1 3 3 3 2 1
0 0 1 1 1 1 1 0
2
Deep first solution
code
class Solution(object):
def regionsBySlashes(self, grid):
"""
:type grid: List[str]
:rtype: int
"""
h = len(grid)
w = h
b = 3
nh, nw = b * h, b * w
table = [[0 for j in range(nw)] for i in range(nh)]
details = [[0 for j in range(nw + 2)] for i in range(nh + 2)]
for i in range(h):
for j in range(w):
if grid[i][j] == ' ':
continue
if grid[i][j] == '/':
for k in range(b):
table[b * i + k][b * j + b - 1 - k] = -1
continue
for k in range(b):
table[b * i + k][b * j + k] = -1
def dfs(table, ti, tj, res):
details[ti + 1][tj + 1] += 1
if ti >= 0 and ti < nh and tj >= 0 and tj < nw and table[ti][tj] == 0:
table[ti][tj] = res
dfs(table, ti - 1, tj, res)
dfs(table, ti + 1, tj, res)
dfs(table, ti, tj - 1, res)
dfs(table, ti, tj + 1, res)
res = 0
for i in range(nh):
for j in range(nw):
if table[i][j] == 0:
res += 1
dfs(table, i, j, res)
for row in details:
for col in row:
print '\t%d' % col,
print ''
return res
solver = Solution()
solver.regionsBySlashes([" /","/ "])
output
0 1 1 1 1 1 0 0
1 3 3 3 3 1 2 0
1 3 4 4 2 4 2 1
1 3 4 2 4 2 3 1
1 3 2 4 2 4 3 1
1 1 4 2 4 4 3 1
0 2 1 3 3 3 2 1
0 0 1 1 1 1 1 0
2