Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- rows = int(input())
- maze, visited, exits, path, ans = [], [], [], [], []
- start_r, start_c = -1, -1
- for row in range(rows):
- maze.append([])
- visited.append([])
- line = input()
- for col in range(len(line)):
- maze[row].append(line[col] == ' ')
- visited[row].append(0)
- if line[col] == 'k':
- start_r, start_c = row, col
- maze[row][col] = True
- if line[col] == ' ' and ((row == 0 or row == rows - 1) or (col == 0 or col == len(line) - 1)):
- exits.append([row, col])
- # Source https://stackoverflow.com/a/60957101
- def traverse(r: int, c: int):
- # if it is a wall ot it was visited, do nothing
- if not maze[r][c] or visited[r][c]:
- return
- # mark the index as visited
- visited[r][c] = 1
- # add index to the path
- path.append((r, c))
- # if the exit is reached, store the path
- # and pop th last index to traverse other paths
- if [r, c] in exits:
- # any path that reached exit are appended here
- ans.append(list(path))
- path.pop()
- return
- # loop on the neighbours. if they are valid indices, do same
- for k in range(4):
- nwr = r + [-1, 1, 0, 0][k]
- nwc = c + [0, 0, 1, -1][k]
- if 0 <= nwr < len(maze) and 0 <= nwc < len(maze[nwr]):
- traverse(nwr, nwc)
- # after finishing this index, just pop because we do not need it any more
- path.pop()
- return
- traverse(start_r, start_c)
- if len(ans) == 0:
- # fix for when Kate is already on the exit
- if start_c == 0 or start_c == len(maze[0]) - 1 or start_r == 0 or start_r == len(maze) - 1:
- print('Kate got out in 1 moves')
- else:
- print('Kate cannot get out')
- else:
- print(f"Kate got out in {min([len(p) for p in ans])} moves")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement