这篇文章是程序自动发表的,详情可以见
这里
href="http://ounix1xcw.bkt.clouddn.com/github.markdown.css" rel="stylesheet">
href="http://ounix1xcw.bkt.clouddn.com/github.markdown.css" rel="stylesheet">
这是leetcode的第542题--01 Matrix
题目
Given a matrix consists of 0 and 1, find the distance of the nearest 0 for each cell. The distance between two adjacent cells is 1.
Input: 0 0 0 0 1 0 1 1 1 Output: 0 0 0 0 1 0 1 2 1
Note
: The number of elements of the given matrix will not exceed 10,000. There are at least one 0 in the given matrix. The cells are adjacent in only four directions: up, down, left and righ
思路 由于是找最小的步骤,所以可以采用BFS。最开始我用
n1 = len(matrix) n2 = len(matrix[0]) tmp = [0 for k in range(n2)] isVisited = [tmp for k in range(n1)]
来记录是否访问,结果总出现一些奇怪的错误,打印出来,发现上面的创建列表的方法,会使isVisited的元素萨都是tmp,同样的id。因为tmp使可变的,都是同一列表的引用。 可以这样isVisited = [[0]*n2 for i in range(n1)]
,0是基础类型,直接复制,不是引用。 为了简便,使用队列保持有序。为了记录移动的步数,我没有写一个类,而是让用另一个队列与队列列表形成映射。
show me the code
class Solution(object): def updateMatrix(self, matrix): """ :type matrix: List[List[int]] :rtype: List[List[int]] """ from collections import deque ans=[] n1 = len(matrix) n2 = len(matrix[0]) def search(i,j): num = deque([0]) que = deque([(i,j)]) # notice that the initialization of deque should pass an iterable object , # and a tuple should be in a list . while que != []: p,q = que.popleft() count = num.popleft() if matrix[p][q] == 0: return count if p>0 and (p-1,q) not in que : que.append((p-1,q)) num.append(count 1) if p<n1-1 and (p 1,q) not in que: que.append((p 1,q)) num.append(count 1) if q>0 and (p,q-1) not in que: que.append((p,q-1)) num.append(count 1) if q<n2-1 and (p,q 1) not in que: que.append((p,q 1)) num.append(count 1) for i in range(n1): ans.append([]) for j in range(n2): ans[i].append(search(i,j)) return ans