import sys # # Buggy Robot: Nick Sharp # def main(): ### Parse input lines = [l.rstrip('\n') for l in sys.stdin] gridH, gridW = [int(x) for x in lines[0].split()] grid = [] for h in range(gridH): gVals = lines[h+1].strip() grid.append(gVals) # Look for the start f = gVals.find("R") if(f != -1): initX = f initY = h origCommand = lines[gridH + 1].strip() ### Function to advance one step def step(x, y, command): if command == 'U': nx = x ny = y-1 if command == 'D': nx = x ny = y+1 if command == 'L': nx = x-1 ny = y if command == 'R': nx = x+1 ny = y if(nx < 0 or nx >= gridW or ny < 0 or ny >= gridH): return (x,y) if(grid[ny][nx] == '#'): return (x,y) return (nx, ny) ### Fill the initial state list # States are stored as (origCommandIndex, gridX, gridY) currStates = [] seenStates = set() currStates.append((0, initX, initY)) seenStates.add((0, initX, initY)) ### Expand a BFS over the states nEdits = 0 while(True): # First, grow the set by inserting nothing # This has the same cost as the current operation, so add it to this # iteration's set rather than the next iteration. currInd = 0 while(currInd < len(currStates)): s = currStates[currInd] if(s[0] < len(origCommand)): nextX, nextY = step(s[1], s[2], origCommand[s[0]]) newS = (s[0]+1, nextX, nextY) if newS not in seenStates: seenStates.add(newS) currStates.append(newS) currInd += 1 # Compute the next round of states by editing each of the current states newStates = [] while currStates: s = currStates.pop() # Look for a solution in the state from the previous iteration if(grid[s[2]][s[1]] == 'E'): print(nEdits) exit(0) # Insert move for move in ['U','D','L','R']: nextX, nextY = step(s[1], s[2], move) newS = (s[0], nextX, nextY) if newS not in seenStates: seenStates.add(newS) newStates.append(newS) # Delete the next entry if(s[0] < len(origCommand)): newS = (s[0]+1, s[1], s[2]) if newS not in seenStates: seenStates.add(newS) newStates.append(newS) nEdits += 1 currStates = newStates if __name__ == "__main__": main()