[一起来刷leetcode吧][25]--No.542 01 Matrix

这篇文章是程序自动发表的,详情可以见 这里
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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值