the Moore neighborhood
the Moore neighborhood
ricardohn 发表于2年前
the Moore neighborhood
  • 发表于 2年前
  • 阅读 7
  • 收藏 0
  • 点赞 2
  • 评论 0

标题:腾讯云 新注册用户域名抢购1元起>>>   

求矩阵中任一点邻居为1 的数量:

def count_neighbours(grid, row, col):
    NEIGHBORS = ((-1, -1), (-1, 0), (-1, 1), (0, -1),
              (0, 1), (1, -1), (1, 0), (1, 1))
    count = 0
    for diff in NEIGHBORS:
        n_row = row + diff[0]
        n_col = col + diff[1]
        if 0<=n_row<len(grid) and 0<=n_col<len(grid[0]):
            if grid[n_row][n_col]:
                count+=1
    return count

if __name__ == '__main__':
    #These "asserts" using only for self-checking and not necessary for auto-testing
    assert count_neighbours(((1, 0, 0, 1, 0),
                             (0, 1, 0, 0, 0),
                             (0, 0, 1, 0, 1),
                             (1, 0, 0, 0, 0),
                             (0, 0, 1, 0, 0),), 1, 2) == 3, "1st example"
    assert count_neighbours(((1, 0, 0, 1, 0),
                             (0, 1, 0, 0, 0),
                             (0, 0, 1, 0, 1),
                             (1, 0, 0, 0, 0),
                             (0, 0, 1, 0, 0),), 0, 0) == 1, "2nd example"
    assert count_neighbours(((1, 1, 1),
                             (1, 1, 1),
                             (1, 1, 1),), 0, 2) == 3, "Dense corner"
    assert count_neighbours(((0, 0, 0),
                             (0, 1, 0),
                             (0, 0, 0),), 1, 1) == 0, "Single"

 

共有 人打赏支持
粉丝 1
博文 76
码字总数 30236
×
ricardohn
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: