图深度遍历的一题
本文章原发于博客园,其他可能是本人的日志同步
问题:
输入一个n*n的方块,统计连块的个数,连块就是有公共的边或者顶点
代码:
mat = [] def init_mat(n): for i in range(0,n+2): # add the edge of the mat mat.append([0] * (n+2)) define_mat(n+1) def define_mat(n): c = 0 stop = 'n' while stop != 'y': row = input("row?: ") col = input("col?: ") mat[row][col] = -1 stop = raw_input("stop?: ") for i in range(1, n): for j in range(1, n): if mat[i][j] == -1: c = c + 1 dfs(i, j, c, n) for i in range(1, n): print mat[i][1:n] def dfs(i, j, c, n): # eight ways (i+1, j) (i-1,j) (i, j+1) (i, j-1) (i-1,j-1) (i-1, j+1) (i+1, j-1) (i+1, j+1) if mat[i][j] == -1 and 0 < i < n and 0 < j < n: mat[i][j] = c dfs(i+1, j, c, n) dfs(i+1, j, c, n) dfs(i-1,j, c, n) dfs(i, j+1, c, n) dfs(i, j-1, c, n) dfs(i-1,j-1, c, n) dfs(i-1, j+1, c, n) dfs(i+1, j-1, c, n) dfs(i+1, j+1, c, n) else: return c