File tree Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Original file line number Diff line number Diff line change
1
+ ## 542 01 Matrix
2
+
3
+ #### Description
4
+
5
+ [ link] ( https://leetcode.com/problems/01-matrix/ )
6
+
7
+ ---
8
+
9
+ #### Solution
10
+
11
+ 两遍循环的解法,对这种题目很有帮助
12
+
13
+ ---
14
+
15
+ #### Code
16
+
17
+ > O(n^2)
18
+
19
+ ``` python
20
+ class Solution :
21
+ def updateMatrix (self , matrix : List[List[int ]]) -> List[List[int ]]:
22
+ m, n = len (matrix), len (matrix and matrix[0 ])
23
+ for i in range (m):
24
+ for j in range (n):
25
+ if matrix[i][j] != 0 :
26
+ matrix[i][j] = float (" inf" )
27
+ if i > 0 and matrix[i - 1 ][j] + 1 < matrix[i][j]:
28
+ matrix[i][j] = matrix[i - 1 ][j] + 1
29
+ if j > 0 and matrix[i][j - 1 ] + 1 < matrix[i][j]:
30
+ matrix[i][j] = matrix[i][j - 1 ] + 1
31
+ for i in range (m - 1 , - 1 , - 1 ):
32
+ for j in range (n - 1 , - 1 , - 1 ):
33
+ if matrix[i][j] != 0 :
34
+ if i + 1 < m and matrix[i + 1 ][j] + 1 < matrix[i][j]:
35
+ matrix[i][j] = matrix[i + 1 ][j] + 1
36
+ if j + 1 < n and matrix[i][j + 1 ] + 1 < matrix[i][j]:
37
+ matrix[i][j] = matrix[i][j + 1 ] + 1
38
+ return matrix
39
+ ```
You can’t perform that action at this time.
0 commit comments