I tried to solve AtCoder's depth-first search (DFS) in Python (result: TLE ...)

Purpose

・ After studying Python, I've been doing a lot of competitive programming lately. When solving the past questions, I stumbled upon a depth-first search, so I summarized the solution. The challenged problem was a depth-first search for Problem A in Typical Contest 001. https://atcoder.jp/contests/atc001/tasks/dfs_a

answer


class Dfs():
    def dfs(self, h, w, maze, init):
        search_stack = [init] #Store initial coordinates in search stack
        fin = [] #Define the completion stack
        while search_stack:
            latest = search_stack.pop() #Extract your location from the search stack
            if maze[latest[0]][latest[1]] == "g": #Output Yes if your current location is Goal
                print("Yes")
                exit()
            else:
                fin.append(latest) #Store the searched coordinates on the completion stack
                candi = [(latest[0]-1, latest[1]), (latest[0]+1, latest[1]), (latest[0], latest[1]-1), (latest[0], latest[1]+1)] #Define coordinate candidates
                for (ny, nx) in candi:
                    if self.check_range(h, w, ny, nx): #Determine if the coordinate candidates are out of range
                        if self.check_wall(maze, ny, nx): #Determine if the coordinate candidate is a wall
                            if not (ny, nx)  in search_stack and not (ny, nx) in fin: #Determine if coordinate candidates are included in the search stack and completion stack
                                search_stack.append((ny, nx)) #Store in search stack
                                continue
        print("No")                    
        
    def check_range(self, h, w, y, x):
        if x > w-1 or x < 0:
            return False
        elif y > h-1 or y < 0:
            return False
        else:
            return True
    
    def check_wall(self, maze, y, x):
        if maze[y][x] == "#":
            return False
        else: 
            return True

if __name__ == "__main__":
    h,w = map(int,input().split())
    maze = [list(input()) for i in range(h)]
    for y, row in enumerate(maze):
        try:
            init = (y, row.index("s")) #Search for a starting point
            d = Dfs()
            d.dfs(h, w, maze, init)
            break
        except ValueError:
            pass

Recommended Posts

I tried to solve AtCoder's depth-first search (DFS) in Python (result: TLE ...)
Algorithm in Python (depth-first search, dfs)
I tried to implement PLSA in Python
I tried to implement permutation in Python
I tried to implement PLSA in Python 2
I tried to implement ADALINE in Python
I wanted to solve ABC159 in Python
I tried to implement PPO in Python
I tried to implement TOPIC MODEL in Python
I tried to implement selection sort in python
I tried to graph the packages installed in Python
I tried to solve the soma cube with python
I tried to implement Dragon Quest poker in Python
I tried to summarize how to use pandas in python
I tried to solve the problem with Python Vol.1
Implement Depth-First Search (DFS) and Breadth-First Search (BFS) in python
I tried to solve AOJ's number theory with Python
[Python] DFS (Depth-first Search) ATC001A
[Python] DFS (Depth-first Search) ABC157D
[For beginners in competition professionals] I tried to solve 40 AOJ "ITP I" questions with python
I tried to implement a one-dimensional cellular automaton in Python
I tried "How to get a method decorated in Python"
I tried to implement the mail sending function in Python
I tried to make a stopwatch using tkinter in python
I tried to implement blackjack of card game in Python
I tried to touch Python (installation)
Write a depth-first search in Python
I tried Line notification in Python
Depth-first search using stack in Python
I tried to solve the ant book beginner's edition with python
I want to solve APG4b with Python (only 4.01 and 4.04 in Chapter 4)
I tried "Implementing a genetic algorithm (GA) in python to solve the traveling salesman problem (TSP)"
I tried to summarize Python exception handling
I wanted to solve ABC160 with Python
I tried using Bayesian Optimization in Python
I tried to let optuna solve Sudoku
I tried to solve TSP with QAOA
[Python] I tried to calculate TF-IDF steadily
I tried to touch Python (basic syntax)
I wanted to solve ABC172 with Python
[Python] I tried to summarize the set type (set) in an easy-to-understand manner.
How to write offline real time I tried to solve E11 with python
I tried to implement Bayesian linear regression by Gibbs sampling in python
I want to batch convert the result of "string" .split () in Python
I tried to develop a Formatter that outputs Python logs in JSON
I tried to implement a card game of playing cards in Python
How to write offline real time I tried to solve E12 with python
I tried to implement merge sort in Python with as few lines as possible
I want to do Dunnett's test in Python
[Python] I tried to solve 100 past questions that beginners and intermediates should solve [Part 5/22]
I wanted to solve NOMURA Contest 2020 with Python
I tried to create a class that can easily serialize Json in Python
I was able to recurse in Python: lambda
I want to create a window in Python
[Python] I tried to solve 100 past questions that beginners and intermediates should solve [Part7 / 22]
I tried playing a typing game in Python
I tried to integrate with Keras in TFv1.1
I tried simulating the "birthday paradox" in Python
I tried the least squares method in Python
I wrote "Introduction to Effect Verification" in Python
I tried to get CloudWatch data with Python