Implement Depth-First Search (DFS) and Breadth-First Search (BFS) in python

What i did

AtCoder Typical Contest 001 A-I implemented depth-first search in python. Since this problem can be solved by either depth-first search (DFS) or breadth-first search (BFS), we implemented both. Depth-first search was implemented with a pattern using a recursive function and a pattern using a stack (LIFO).

DFS

Cases using recursive functions


#A Depth-first search recursive function
import sys
sys.setrecursionlimit(10**7) #Recursive function call restrictions

def dfs(v_x, v_y, seen_list, c_list):
    if v_x < 0 or v_y < 0 or v_x >= w or v_y >= h:
        return
    if seen_list[v_y][v_x]:
        return
    if c_list[v_y][v_x] == "#":
        return
    seen_list[v_y][v_x] = True
    dfs(v_x+1,v_y,seen_list,c_list)
    dfs(v_x-1,v_y,seen_list,c_list)
    dfs(v_x,v_y+1,seen_list,c_list)
    dfs(v_x,v_y-1,seen_list,c_list)
    
h, w = map(int, input().split())
seen_list = [[False] * w for i in range(h)]
c_list = []
s = []
g = []
for i in range(h):
    _tmp = list(input())
    if "s" in _tmp:
        s = [_tmp.index("s"),i]
    if "g" in _tmp:
        g = [_tmp.index("g"),i]
    c_list.append(_tmp)

dfs(s[0],s[1],seen_list,c_list)

if seen_list[g[1]][g[0]]:
    print("Yes")
else:
    print("No")

Case using stack

#A Depth-first search stack(LIFO)
from collections import deque

def dfs(stack, seen_list, c_list):
    while len(stack)>0:
        v_x, v_y = stack.pop()
        if v_x < 0 or v_y < 0 or v_x >= w or v_y >= h:
            continue
        if seen_list[v_y][v_x]:
            continue
        if c_list[v_y][v_x] == "#":
            continue
        seen_list[v_y][v_x] = True
        stack.append([v_x+1,v_y])
        stack.append([v_x-1,v_y])
        stack.append([v_x,v_y+1])
        stack.append([v_x,v_y-1])
    
h, w = map(int, input().split())
seen_list = [[False] * w for i in range(h)]
c_list = []
s = []
g = []
stack = deque()

for i in range(h):
    _tmp = list(input())
    if "s" in _tmp:
        s = [_tmp.index("s"),i]
    if "g" in _tmp:
        g = [_tmp.index("g"),i]
    c_list.append(_tmp)

stack.append(s)
dfs(stack,seen_list,c_list)

if seen_list[g[1]][g[0]]:
    print("Yes")
else:
    print("No")

BFS

#A Depth-first search Queue to solve with breadth-first search(FIFO)
from collections import deque

def bfs(que, seen_list, c_list):
    while len(que)>0:
        v_x, v_y = que.pop()
        if v_x < 0 or v_y < 0 or v_x >= w or v_y >= h:
            continue
        if seen_list[v_y][v_x]:
            continue
        if c_list[v_y][v_x] == "#":
            continue
        seen_list[v_y][v_x] = True
        que.appendleft([v_x+1,v_y])
        que.appendleft([v_x-1,v_y])
        que.appendleft([v_x,v_y+1])
        que.appendleft([v_x,v_y-1])
    
h, w = map(int, input().split())
seen_list = [[False] * w for i in range(h)]
c_list = []
s = []
g = []
que = deque()

for i in range(h):
    _tmp = list(input())
    if "s" in _tmp:
        s = [_tmp.index("s"),i]
    if "g" in _tmp:
        g = [_tmp.index("g"),i]
    c_list.append(_tmp)

que.append(s)
bfs(que,seen_list,c_list)

if seen_list[g[1]][g[0]]:
    print("Yes")
else:
    print("No")

Recommended Posts

Implement Depth-First Search (DFS) and Breadth-First Search (BFS) in python
[Python] Depth-first search and breadth-first search
Algorithm in Python (depth-first search, dfs)
[Python] BFS (breadth-first search) ABC168D
[Python] DFS (Depth-first Search) ATC001A
[Python] DFS (Depth-first Search) ABC157D
[Python] BFS (breadth-first search) ABC007C
Write a depth-first search in Python
Depth-first search using stack in Python
Implement FIR filters in Python and C
Search and play YouTube videos in Python
I tried to solve AtCoder's depth-first search (DFS) in Python (result: TLE ...)
Implement Enigma in python
Python Exercise 1-Breadth-first search
Binary search in Python
Implement recommendations in Python
Implement XENO in python
Linear search in Python
Implement sum in Python
Binary search in Python (binary search)
Implement Traceroute in Python 3
I implemented breadth-first search in python (queue, drawing self-made)
Search for strings in Python
Breadth-first search / bidirectional search (Python version)
Implement naive bayes in Python 3.3
Implement ancient ciphers in python
Binary search in Python / C ++
Algorithm in Python (binary search)
Stack and Queue in Python
Implement Redis Mutex in Python
Implement extension field in Python
Implement fast RPC in Python
Implement method chain in Python
Implement Dijkstra's Algorithm in python
Implement Slack chatbot in Python
Unittest and CI in Python
Application to display and search local memos (diary) in Python
Solving with Ruby and Python AtCoder ABC151 D Breadth-first search
Implement stacking learning in Python [Kaggle]
Find the critical path of PERT using breadth-first search and depth-first search
Write a binary search in Python
MIDI packages in Python midi and pretty_midi
Implement R's power.prop.test function in python
Depth-first search (non-recursive type) and lower limit pruning method (Python edition)
Difference between list () and [] in Python
View photos in Python and html
Sorting algorithm and implementation in Python
Manipulate files and folders in Python
About dtypes in Python and Cython
Implement the Singleton pattern in Python
Assignments and changes in Python objects
Check and move directories in Python
Ciphertext in Python: IND-CCA2 and RSA-OAEP
Hashing data in R and Python
Function synthesis and application in Python
Export and output files in Python
Quickly implement REST API in Python
Reverse Hiragana and Katakana in Python2.7
[GUI in Python] PyQt5-Menu and Toolbar-
Create and read messagepacks in Python
Python 2-minute search and its derivation