[프로그래머스] DFS/BFS

김지원·2022년 10월 24일
0
post-custom-banner

네트워크

from collections import defaultdict
   

def solution(n, computers):
    global answer
    answer=0
    net={k:[] for k in range(0,n)}
    for i in range(len(computers)):
        for j in range(len(computers[0])):
            if i!=j and computers[i][j]==1:
                net[i].append(j)
    visited=set()

    def dfs(node):
        global answer
        if node in visited:
            return
        visited.add(node)
        for next_n in net[node]:
            if next_n not in visited:
                dfs(next_n)
    
    for node in net.keys():
        if node in visited:
            continue         
        answer+=1
        dfs(node)
    return answer

게임 맵 최단거리

from collections import deque
def solution(maps): 
    n,m=len(maps)-1,len(maps[0])-1
    pos=[(1,0),(0,1),(-1,0),(0,-1)]
    visited=[[0]*(m+1) for _ in range(n+1)]
    maps[n][m]=-1
    
    # 도달하지 못할 경우
    if maps[n-1][m]==0 and maps[n][m-1]==0:
        return -1
    routes=deque([(0,0,1)])
    while routes: 
        x, y, cnt=routes.popleft()
        for nx,ny in pos:
            nx_pos, ny_pos=x+nx, y+ny
            if 0<=nx_pos<=n and 0<=ny_pos<=m and maps[nx_pos][ny_pos] and visited[nx_pos][ny_pos]==0:
                visited[nx_pos][ny_pos]=1
                maps[nx_pos][ny_pos]=cnt+1
                routes.append((nx_pos,ny_pos,cnt+1))
    
    return maps[n][m]
profile
Make your lives Extraordinary!
post-custom-banner

0개의 댓글