yuns

dfs예시 본문

algorithms/#5 DFS and BFS

dfs예시

yuuuun 2020. 11. 10. 14:48
반응형

아이스크림

n, m = map(int, input().split())
graph = []
for i in range(n):
    graph.append(list(map(int, input())))

def dfs(x, y):
    if x <= -1 or x >= n or y >= m or y <= -1:
        return False
    #방문하지 않은 경우
    if graph[x][y] == 0:
        graph[x][y] = 1
        #상하 좌우 4가지 경우 고려
        dfs(x - 1, y)
        dfs(x, y - 1)
        dfs(x + 1, y)
        dfs(x, y+1)
        return True
    return False

result = 0

for i in range(n):
    for j in range(m):
        if dfs(i, j) == True:
            result += 1
print(result)

미로 탈출

from collections import deque
n, m = map(int, input().split())

graph = []
for i in range(n):
    graph.append(list(map(int, input())))

dx = [-1, 1, 0, 0]
dy = [0, 0, 1, -1]
def bfs(x, y):
    queue = deque()
    queue.append((x, y))
    #queue가 빌 때 까지 계속 진행
    while queue:
        x, y = queue.popleft()
        for i in range(4):
            nx = x + dx[i]
            ny = y + dy[i]
            if nx < 0 or ny < 0 or nx >= n or ny >= m:
                continue
            if graph[nx][ny] == 0:
                continue
            if graph[nx][ny] == 1:
                graph[nx][ny] = graph[x][y] + 1
                queue.append((nx, ny))
        
    return graph[n - 1][m - 1]
print(bfs(0, 0))
반응형

'algorithms > #5 DFS and BFS' 카테고리의 다른 글

DFS vs BFS  (0) 2020.11.07
BFS: 너비 우선 탐색  (0) 2020.11.07
DFS: 깊이 우선 탐색  (0) 2020.11.07
자료구조 기초  (0) 2020.11.07
Comments