Doing/Python
Recursion. Finding Maze Path and Counting Cells in a Blob
YongArtist
2020. 9. 16. 19:21
강의 내용을 보고 직접 구현해보았는데, 생각보다 어렵지 않았다. 코드로 구현하기 전 전체적으로 어떻게 동작하는지에 대한 사고가 있다면 쉽게 접근할 수 있어 보인다. colorscripter.com/info#e"이러면서 조금씩 재귀에 대한 이해도가 올라가는 기분이다 훅훅
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 | from pprint import pprint maze = [[0, 0, 0, 0, 0, 0, 0, 1], [0, 1, 1, 0, 1, 1, 0, 1], [0, 0, 0, 1, 0, 0, 0, 1], [0, 1, 0, 0, 1, 1, 0, 0], [0, 1, 1, 1, 0, 0, 1, 1], [0, 1, 0, 0, 0, 1, 0, 1], [0, 0, 0, 1, 0, 0, 0, 1], [0, 1, 1, 1, 0, 1, 0, 0]] grid = [[1, 0, 0, 0, 0, 0, 0, 1], [0, 1, 1, 0, 0, 1, 0, 0], [1, 1, 0, 0, 1, 0, 1, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 1, 0, 1, 0, 1, 0, 0], [0, 1, 0, 1, 0, 1, 0, 0], [1, 0, 0, 0, 1, 0, 0, 1], [0, 1, 1, 0, 0, 1, 1, 1]] def find_path(x, y): # pathWay = 0 # wall = 1 # blocked = 2 # path = 3 size = len(maze) if x < 0 or y < 0 or x >= size or y >= size: return False elif maze[x][y] != 0: return False elif x == size - 1 and y == size - 1: maze[x][y] = 3 return True else: maze[x][y] = 3 if find_path(x, y + 1) or find_path(x, y - 1) or find_path(x + 1, y) or find_path(x - 1, y): return True maze[x][y] = 2 return False def count_cells(x, y): # red : 2 size = len(grid) cnt = 0 if x < 0 or y < 0 or x >= size or y >= size: return 0 elif grid[x][y] != 1: return 0 else: grid[x][y] = 2 return 1 + count_cells(x - 1, y) + count_cells(x - 1, y + 1) \ + count_cells(x, y + 1) + count_cells(x + 1, y + 1) \ + count_cells(x + 1, y) + count_cells(x + 1, y - 1) \ + count_cells(x, y - 1) + count_cells(x - 1, y - 1) if __name__ == '__main__': # Finding Maze Path if find_path(1, 8): print("Found path") pprint(maze) else: print("Not found path") pprint(maze) # Counting Cells in a Blob print(count_cells(0, 0)) | cs |