the Moore neighborhood
2016-05-10 00:00
281 查看
求矩阵中任一点邻居为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"
相关文章推荐
- 输出字符串中出现次数最多的字符
- 灵活多变的flex 格式
- 强大的Vue.js
- Redis缓存技术
- 中文分词工具
- IK Analyzer分词及词频统计Java简单实现
- 被angular的错误提示吓到了
- 云计算带来的不同于传统运维的应用层面的三个挑战:
- 怎么实现iMindMap中的流程图的快速运用
- 策略模式与开发实践
- Android SharedPreferences 源码分析
- 理解Android编译命令
- SwiftClosure
- Multi thread: std::async()和std::future(1)
- BestCoder Round #81 (div.2) A,B,C
- jQuery 测试案例(一)
- MySQL联合索引是不支持不同排序规则解决方案
- mysql Using temporary Using filesort 优化
- java 内部类
- 你知道Windows上有哪些奇技淫巧吗?