Skip to content

Commit b9b76a9

Browse files
authored
Create 01-matrix.py
1 parent 51a974c commit b9b76a9

1 file changed

Lines changed: 61 additions & 0 deletions

File tree

Python/01-matrix.py

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
# Time: O(n)
2+
# Space: O(n)
3+
4+
# Given a matrix consists of 0 and 1, find the distance of the nearest 0 for each cell.
5+
# The distance between two adjacent cells is 1.
6+
#
7+
# Example 1:
8+
#
9+
# Input:
10+
# 0 0 0
11+
# 0 1 0
12+
# 0 0 0
13+
#
14+
# Output:
15+
# 0 0 0
16+
# 0 1 0
17+
# 0 0 0
18+
#
19+
# Example 2:
20+
#
21+
# Input:
22+
# 0 0 0
23+
# 0 1 0
24+
# 1 1 1
25+
#
26+
# Output:
27+
# 0 0 0
28+
# 0 1 0
29+
# 1 2 1
30+
#
31+
# Note:
32+
# The number of elements of the given matrix will not exceed 10,000.
33+
# There are at least one 0 in the given matrix.
34+
# The cells are adjacent in only four directions: up, down, left and right.
35+
36+
class Solution(object):
37+
def updateMatrix(self, matrix):
38+
"""
39+
:type matrix: List[List[int]]
40+
:rtype: List[List[int]]
41+
"""
42+
queue = collections.deque([])
43+
for i in xrange(len(matrix)):
44+
for j in xrange(len(matrix[0])):
45+
if matrix[i][j] == 0:
46+
queue.append((i, j))
47+
else:
48+
matrix[i][j] = float("inf")
49+
50+
dirs = [(-1, 0), (1, 0), (0, -1), (0, 1)]
51+
while queue:
52+
cell = queue.popleft()
53+
for dir in dirs:
54+
i, j = cell[0]+dir[0], cell[1]+dir[1]
55+
if not (0 <= i < len(matrix)) or not (0 <= j < len(matrix[0])) or \
56+
matrix[i][j] <= matrix[cell[0]][cell[1]]+1:
57+
continue
58+
queue.append((i, j))
59+
matrix[i][j] = matrix[cell[0]][cell[1]]+1
60+
61+
return matrix

0 commit comments

Comments
 (0)