[알고리즘] BFS

그녕·2024년 5월 16일
0

알고리즘 문제 풀이

목록 보기
36/37
post-thumbnail

1. 프로그래머스_ 게임맵 최단거리

문제링크

from collections import deque # deque 선언

def solution(maps):
    dx,dy=[-1,1,0,0],[0,0,-1,1]
    q = deque()
    a = len(maps)
    b = len(maps[0])
    q.append((0,0))
    while q:
        x,y = q.popleft()
        for i in range(4):
            nx= x+dx[i]
            ny = y+dy[i]
            if 0<=nx<a and 0<=ny<b:
                if maps[nx][ny]==1:
                    maps[nx][ny]=maps[x][y]+1
                    q.append((nx,ny))
    if maps[a-1][b-1] != 1: # 만약 1이 아니라면 해당 경우는 가로막히지 않은 경우
        return maps[a-1][b-1] # 값 리턴
    else:
        return -1 # 가로막혀서 접근 불가인 경우 -1 리턴
    

2. 프로그래머스_ 타겟 넘버

문제 링크

def solution(numbers, target):
    answer = 0
    ans=[0]
    for i in numbers:
        temp=[]
        for j in ans:
            temp.append(j+i)
            temp.append(j-i)
        ans=temp
    # print(ans)
    for i in ans:
        if i == target:
            answer+=1
    return answer
#no

3. 백준_단지번호 붙이기

문제 링크

from collections import deque

dx = [0, 0, 1, -1]
dy = [1, -1, 0, 0]


def bfs(graph, a, b):
    n = len(graph)
    queue = deque()
    queue.append((a, b))
    graph[a][b] = 0
    count = 1

    while queue:
        x, y = queue.popleft()
        for i in range(4):
            nx = x + dx[i]
            ny = y + dy[i]
            if nx < 0 or nx >= n or ny < 0 or ny >= n:
                continue
            if graph[nx][ny] == 1:
                graph[nx][ny] = 0
                queue.append((nx, ny))
                count += 1
    return count


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

cnt = []
for i in range(n):
    for j in range(n):
        if graph[i][j] == 1:
            cnt.append(bfs(graph, i, j))

cnt.sort()
print(len(cnt))
for i in range(len(cnt)):
    print(cnt[i])
profile
AI 개발자

0개의 댓글