|
| 1 | +""" |
| 2 | +First, set the distance to 0 when `i` and `j` in the `matrix` is 0. [0] |
| 3 | +
|
| 4 | +Second, when an `(i, j)` in the `opt` is 0, its neighbor's distance is 0+1, so |
| 5 | +we set all the `i` and `j` in the `opt` where its distance is 1. |
| 6 | +then set all the `i` and `j` in the `opt` where its distance is 2. |
| 7 | +then set all the `i` and `j` in the `opt` where its distance is 3. |
| 8 | +then set all the `i` and `j` in the `opt` where its distance is 4. |
| 9 | +... |
| 10 | +
|
| 11 | +the `count` is the number of distance that we found. |
| 12 | +While we haven't find all the answer, we keep on doing above operation. [1] |
| 13 | +
|
| 14 | +The time comlexity is `O(N^2)`, **N is the number of element in the 2D matrix**. |
| 15 | +The space complexity is `O(N)`, where we store the `opt`. |
| 16 | +""" |
| 17 | +class Solution(object): |
| 18 | + def updateMatrix(self, matrix): |
| 19 | + def setDistance(i, j, dis): |
| 20 | + if i<0 or i>=M: return False |
| 21 | + if j<0 or j>=N: return False |
| 22 | + if opt[i][j]!=-1: return False #opt[i][j]==-1 means the value is set already, skip. |
| 23 | + opt[i][j] = dis |
| 24 | + return True |
| 25 | + |
| 26 | + M, N = len(matrix), len(matrix[0]) |
| 27 | + opt = [[-1]*N for _ in xrange(M)] |
| 28 | + dis = 0 |
| 29 | + count = 0 |
| 30 | + |
| 31 | + #[0] |
| 32 | + for i in xrange(M): |
| 33 | + for j in xrange(N): |
| 34 | + if matrix[i][j]==0: |
| 35 | + count+=1 |
| 36 | + opt[i][j] = 0 |
| 37 | + |
| 38 | + while count<M*N: |
| 39 | + for i in xrange(M): |
| 40 | + for j in xrange(N): |
| 41 | + if opt[i][j]==dis: |
| 42 | + if setDistance(i+1, j, dis+1): count+=1 |
| 43 | + if setDistance(i-1, j, dis+1): count+=1 |
| 44 | + if setDistance(i, j+1, dis+1): count+=1 |
| 45 | + if setDistance(i, j-1, dis+1): count+=1 |
| 46 | + dis+=1 |
| 47 | + return opt |
| 48 | + |
| 49 | +""" |
| 50 | +Standard BFS |
| 51 | +The same idea, but use BFS to implement. |
| 52 | +The time complexity is `O(N)`, **N is the number of element in the 2D matrix**. |
| 53 | +The space complexity is `O(N)`, where we store the `opt`. |
| 54 | +""" |
| 55 | +class Solution(object): |
| 56 | + def updateMatrix(self, matrix): |
| 57 | + M, N = len(matrix), len(matrix[0]) |
| 58 | + opt = [[-1]*N for _ in xrange(M)] |
| 59 | + q = collections.deque([]) |
| 60 | + |
| 61 | + for i in xrange(M): |
| 62 | + for j in xrange(N): |
| 63 | + if matrix[i][j]==0: |
| 64 | + q.append((i, j, 0)) |
| 65 | + |
| 66 | + while q: |
| 67 | + i, j, dis = q.popleft() |
| 68 | + if i<0 or i>=M: continue |
| 69 | + if j<0 or j>=N: continue |
| 70 | + if opt[i][j]!=-1: continue |
| 71 | + opt[i][j] = dis |
| 72 | + |
| 73 | + for ni, nj in [(i+1, j), (i-1, j), (i, j+1), (i, j-1)]: |
| 74 | + q.append((ni, nj, dis+1)) |
| 75 | + |
| 76 | + return opt |
| 77 | + |
| 78 | + |
| 79 | + |
0 commit comments