Castle on the Grid

  • + 0 comments

    Using BFS

    def is_valid(grid, i, j):
        return i >=0 and i < len(grid) and j >=0 and j < len(grid[i]) and grid[i][j] != 'X'
        
    def span(grid, x, y, graph):
        i, j = x+1, y
        while is_valid(grid, i, j):
            graph[(x, y)].add((i, j))
            i = i+1
        
        i, j = x-1, y
        while is_valid(grid, i, j):
            graph[(x, y)].add((i, j))
            i = i-1
            
        i, j = x, y+1
        while is_valid(grid, i, j):
            graph[(x, y)].add((i, j))
            j = j+1
        
        i, j = x, y-1
        while is_valid(grid, i, j):
            graph[(x, y)].add((i, j))
            j = j-1
        
    def build_graph(grid):
        graph = {}
        for i in range(len(grid)):
            for j in range(len(grid[i])):
                if (grid[i][j] != 'X'):
                    graph[(i, j)] = set()
                    span(grid, i, j, graph)
        return graph
    
    def bfs(start, end, graph):
        q1 = deque()
        q2 = deque()
        
        visited = set()
        
        q1.append(start)
        depth = 0
        
        while len(q1) > 0:
            v = q1.popleft()
            if v == end:
                return depth
            for adj in graph[v]:
                if adj not in visited:
                    visited.add(adj)
                    q2.append(adj)
            if len(q1) == 0 and len(q2) > 0:
                depth = depth + 1
                q1, q2 = q2, q1
        
        return depth
    
    def minimumMoves(grid, startX, startY, goalX, goalY):
        graph = build_graph(grid)
        start = (startX, startY)
        end = (goalX, goalY)
        return bfs(start, end, graph)