最近迷宫游戏很火呦~ 连同路径跟迷宫本质上没有差别
不是很清楚你后面要算什么东西,不过这代码把全部 0 被包围的个数都数出来了- maze = [[0,0,1,0,1,0,1,1,1,0,1,0,1,1,1,0,0,0,1,0,1,0,1],
- [0,0,1,0,1,0,1,0,0,0,1,0,0,0,1,0,0,0,1,0,1,0,1],
- [1,0,1,0,1,0,1,0,1,0,1,1,1,1,1,1,1,1,1,0,1,1,1],
- [1,0,1,0,1,0,1,0,1,0,1,0,0,0,0,0,0,0,0,0,1,0,1],
- [1,1,1,0,1,1,1,1,1,0,1,0,1,1,1,1,1,0,1,1,1,0,1],
- [1,0,0,0,0,0,1,0,1,0,1,0,0,0,1,0,0,0,1,0,0,0,1],
- [1,1,1,1,1,0,1,1,1,0,1,0,1,0,1,1,1,0,1,1,1,1,1],
- [1,0,0,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,0],
- [1,0,0,0,1,1,1,0,1,0,1,0,1,1,1,0,1,0,1,0,1,0,0]]
- for each in maze:
- print(each)
- print()
- def countZeros():
- Row = len(maze)
- Col = len(maze[0])
- maze2 = []
- marked = 'X'
- for each in maze:
- maze2.append(each[:])
- counts = 1
- def countingZeros(x, y):
- nonlocal maze2
- nonlocal counts
- maze2[x][y] = marked
-
- move_x = [1,0,-1,0]
- move_y = [0,1,0,-1]
- for i in range(4):
- x1 = x + move_x[i]
- y1 = y + move_y[i]
- if(y1 >= 0 and y1 < Col and x1 >= 0 and x1 < Row):
- if(maze2[x1][y1] == 1 or maze2[x1][y1] == marked):
- continue
- maze2[x1][y1] = marked
- counts += 1
- countingZeros(x1,y1)
- for y in range(Col):
- for x in range(Row):
- if maze2[x][y] == marked or maze2[x][y] == 1 :
- continue
- countingZeros(x,y)
- print("({:2d}, {:2d}) has {:2d} connected component(s)".format(x,y,counts))
- counts = 1
- ## print()
- ## for each in maze2: #打印副本迷宫
- ## for each1 in each:
- ## print("{}".format(each1), end = " ")
- ## print()
-
- countZeros()
复制代码 |