grid_path_bfs_dfs.py

mail@pastecode.io avatar
unknown
plain_text
16 days ago
1.5 kB
9
Indexable
Never
from collections import deque
# bfs
def search_grid_bfs(grid):
    rows, cols = len(grid), len(grid[0])
    queue = deque([(0, 0)])
    grid[0][0] = '1' 
    while queue:
        r, c = queue.popleft()
        if r == rows - 1:  
            return True
        for row, col in [(r, c+1), (r+1, c), (r, c-1), (r-1, c)]:
            if 0 <= row < rows and 0 <= col < cols and grid[row][col] == '0':
                grid[row][col] = '1' 
                queue.append((row, col))
    return False
grid = [
    ['0', '0', '0', '1'],  
    ['1', '0', '0', '0'],  
    ['0', '1', '1', '0'],  
    ['0', '0', '0', '0']   
]
result = search_grid_bfs(grid)
print("Path bool", result)

##############################

# dfs
def search_grid_dfs(grid):
    rows = len(grid)
    cols = len(grid[0])
    def dfs(r, c):
        if (r < 0 or r >= rows or c < 0 or c >= cols or 
                grid[r][c] == '1'):
            return False
        grid[r][c]='1'
        if r == rows-1:
            return True
        '''
        if dfs(r, c + 1):
            return True
        if dfs(r + 1, c):
            return True
        if dfs(r - 1, c):
            return True
        if dfs(r, c - 1):
            return True
        return False
        '''
        return dfs(r, c + 1) or dfs(r, c - 1) or dfs(r+1, c) or dfs(r-1, c)
    return dfs(0,0)

grid = [
    ['0', '0', '0', '1'],  
    ['1', '0', '0', '0'],  
    ['0', '1', '1', '0'],  
    ['0', '0', '0', '0']   
]
result = search_grid_dfs(grid)
print("Path to end:", result)
Leave a Comment