코딩테스트/프로그래머스

[BFS] 무인도 여행

박소민 2023. 12. 17. 03:08
무인도 여행
 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

from collections import deque

def bfs(i,j,n,m,visited,graph):
    dx=[-1,1,0,0]
    dy=[0,0,-1,1]
    
    queue=deque()
    queue.append((i,j))
    visited[i][j]=True
    tmp=int(graph[i][j])
    
    while queue:
        x,y=queue.popleft()
        for k in range(4):
            nx=x+dx[k]
            ny=y+dy[k]
            
            if nx<0 or ny<0 or nx>=n or ny>=m: continue
            if graph[nx][ny]=='X': continue
            if visited[nx][ny]==True: continue
            visited[nx][ny]=True
            tmp+=int(graph[nx][ny])
            queue.append((nx,ny))
        
    return tmp

def solution(maps):
    answer = []
    
    n=len(maps)
    m=len(maps[0])
    
    graph=[]
    for map in maps:
        graph.append(list(map.rstrip()))
    
    visited=[[False for _ in range(m)] for _ in range(n)]
    for i in range(n):
        for j in range(m):
            if graph[i][j]=='X': continue
            if visited[i][j]==True: continue
            answer.append(bfs(i,j,n,m,visited,graph))
    
    if answer:
        answer.sort()
    else:
        answer.append(-1)
    return answer

'코딩테스트 > 프로그래머스' 카테고리의 다른 글

[Union-Find][BFS] 전력망을 둘로 나누기  (1) 2024.01.04
[다익스트라][Heap] 배달  (1) 2023.12.17
[Heap][해시] 베스트 앨범  (1) 2023.12.10
[DFS] 타겟 넘버  (0) 2023.12.03
[DP] 정수 삼각형  (1) 2023.12.02