Code Signal_练习题_Minesweeper

In the popular Minesweeper game you have a board with some mines and those cells that don't contain a mine have a number in it that indicates the total number of mines in the neighboring cells. Starting off with some arrangement of mines we want to create a Minesweeper game setup.

Example

For

matrix = [[true, false, false],
          [false, true, false],
          [false, false, false]]

the output should be

minesweeper(matrix) = [[1, 2, 1],
                       [2, 1, 1],
                       [1, 1, 1]]

Check out the image below for better understanding:

 

我的解答:

 

def minesweeper(matrix):
    ret = []
    w = len(matrix[0])
    dic = {True:1, False:0}
    newMatrix = []
    newMatrix.append([])
    newMatrix.append([])
    for x in range(len(matrix[0])+2):
        newMatrix[0].insert(0,False)
        newMatrix[1].append(False)
    for y in matrix:
        y.append(False)
        y.insert(0,False)
        newMatrix.insert(-1,y)

    for i in range(len(matrix)):
        ret.append([])
        for j in range(w):
            print(newMatrix[i+2][j+2])
            k = int(dic[newMatrix[i][j]]) + int(dic[newMatrix[i][j+1]]) + int(dic[newMatrix[i][j+2]]) + int(dic[newMatrix[i+1][j]]) + int(dic[newMatrix[i+1][j+2]]) + int(dic[newMatrix[i+2][j]]) + int(dic[newMatrix[i+2][j+1]]) + int(dic[newMatrix[i+2][j+2]])
            ret[i].append(k)
    return ret

 

 

def minesweeper(matrix):
    r = []

    for i in range(len(matrix)):
        r.append([])
        for j in range(len(matrix[0])):
            l = -matrix[i][j]
            for x in [-1, 0, 1]:
                for y in [-1, 0, 1]:
                    if 0 <= i + x < len(matrix) and 0 <= j + y < len(matrix[0]):
                        l += matrix[i + x][j + y]

            r[i].append(l)
    return r
膜拜大佬

 

转载于:https://www.cnblogs.com/BlameKidd/p/9465391.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值