[Codewars] 102: Path Finder #1: can you reach the exit?

题目

Task

You are at position [0, 0] in maze NxN and you can only move in one of the four cardinal directions (i.e. North, East, South, West). Return true if you can reach position [N-1, N-1] or false otherwise.

Empty positions are marked .. Walls are marked W. Start and exit positions are empty in all test cases.

我的答案

使用BFS(广度优先搜索算法)

from collections import deque
from math import sqrt, floor

dirc = [[0, 1], [0, -1], [1, 0], [-1, 0]]
d = deque(maxlen=500)

def BFS(n, maze):
    while len(d) > 0:
        d0 = d.popleft()
        for i in range(4):
            x = d0[0] + dirc[i][0]
            y = d0[1] + dirc[i][1]
            if x < 0 or x >= n or y < 0 or y >= n:
                continue
            if maze[x * n + y] == 'W':
                continue
            if x == n - 1 and y == n - 1:
                return True
            maze[x * n + y] = 'W'
            d.append([x, y])
    return False

def path_finder(maze):
    n = floor(sqrt(len(maze)))
    if n == 1:
        return True
    else:
        maze = [i for i in list(maze) if i !='\n']
        while len(d) > 0:
            d.pop()
        d.append([0, 0])
        maze[0] = 'W'
        return BFS(n, maze)

其他精彩答案

def path_finder(maze):
    matrix = list(map(list, maze.splitlines()))
    stack, length = [[0, 0]], len(matrix)
    while len(stack):
      x, y = stack.pop()
      if matrix[x][y] == '.':
        matrix[x][y] = 'x'
        for x, y in (x, y-1), (x, y+1), (x-1, y), (x+1, y):
          if 0 <= x < length and 0 <= y < length:
            stack.append((x, y))
    return matrix[length-1][length-1] == 'x'
def path_finder(maze):
    g = maze.splitlines()
    end, bag = len(g[0]) -1 + len(g) * 1j - 1j, {0}
    grid = {x + y * 1j for y,l in enumerate(g) for x,c in enumerate(l) if '.' == c}
    while bag:
        if end in bag: return True
        grid -= bag
        bag = grid & set.union(*({z + 1j ** k for k in range(4)} for z in bag))
    return False

你可能感兴趣的:([Codewars] 102: Path Finder #1: can you reach the exit?)