happyso
study with happyso
happyso
전체 방문자
오늘
어제
  • 분류 전체보기 (302)
    • GIT (3)
    • 컴퓨터 기본 개념 (29)
    • 알고리즘 (125)
      • 알고리즘 문제 (115)
      • 알고리즘 개념 (10)
    • Go (2)
    • 클라우드 (54)
      • DevOps (4)
      • Kubernetes(쿠버네티스) (33)
      • AWS (6)
      • CKA (8)
    • 리눅스(Linux) (18)
      • 컨테이너(Container) (8)
    • Front (22)
      • JavaScript (2)
      • React (20)
    • Python (21)
      • Python 웹 크롤링 (11)
      • Django (7)
      • MachineLearning (3)
    • 데이터베이스 (6)
      • MariaDB (2)
      • MongoDB (4)
    • C언어 (5)
    • Trouble Shooting (2)
    • 네트워크 (8)
      • CCNA (5)
    • 보안 (1)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • edit
  • apply
  • replace
  • kubernetes
  • 15
  • 18
  • Patch

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
happyso

study with happyso

[python] 백준 > BFS/DFS > 빙산
알고리즘/알고리즘 문제

[python] 백준 > BFS/DFS > 빙산

2021. 1. 28. 23:56

[문제]

지구 온난화로 인하여 북극의 빙산이 녹고 있다. 빙산을 그림 1과 같이 2차원 배열에 표시한다고 하자. 빙산의 각 부분별 높이 정보는 배열의 각 칸에 양의 정수로 저장된다. 빙산 이외의 바다에 해당되는 칸에는 0이 저장된다. 그림 1에서 빈칸은 모두 0으로 채워져 있다고 생각한다.

그림 1. 행의 개수가 5이고 열의 개수가 7인 2차원 배열에 저장된 빙산의 높이 정보

빙산의 높이는 바닷물에 많이 접해있는 부분에서 더 빨리 줄어들기 때문에, 배열에서 빙산의 각 부분에 해당되는 칸에 있는 높이는 일년마다 그 칸에 동서남북 네 방향으로 붙어있는 0이 저장된 칸의 개수만큼 줄어든다. 단, 각 칸에 저장된 높이는 0보다 더 줄어들지 않는다. 바닷물은 호수처럼 빙산에 둘러싸여 있을 수도 있다. 따라서 그림 1의 빙산은 일년후에 그림 2와 같이 변형된다.

그림 3은 그림 1의 빙산이 2년 후에 변한 모습을 보여준다. 2차원 배열에서 동서남북 방향으로 붙어있는 칸들은 서로 연결되어 있다고 말한다. 따라서 그림 2의 빙산은 한 덩어리이지만, 그림 3의 빙산은 세 덩어리로 분리되어 있다.

한 덩어리의 빙산이 주어질 때, 이 빙산이 두 덩어리 이상으로 분리되는 최초의 시간(년)을 구하는 프로그램을 작성하시오. 그림 1의 빙산에 대해서는 2가 답이다. 만일 전부 다 녹을 때까지 두 덩어리 이상으로 분리되지 않으면 프로그램은 0을 출력한다.

 

 

[나의 풀이-첫번째(실패)]

import sys
from collections import deque
input = sys.stdin.readline

N, M = map(int, input().split())
arr = [list(map(int, input().split())) for _ in range(N)]
dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]
division = False
answer = 0


def bfs(x, y):
    global arr
    global visited
    dq = deque()
    dq.append((x, y))
    visited[x][y] = True
    while dq:
        p_x, p_y = dq.popleft()
        for index in range(4):
            s_dx, s_dy = p_x+dx[index], p_y+dy[index]

            if 0 <= s_dx < N and 0 <= s_dy < M:
                if arr[s_dx][s_dy] == 0 and not visited[s_dx][s_dy]:
                    arr[p_x][p_y] -= 1
                    if arr[p_x][p_y] < 0:
                        arr[p_x][p_y] = 0

                if arr[s_dx][s_dy] > 0 and not visited[s_dx][s_dy]:
                    dq.append((s_dx, s_dy))
                    visited[s_dx][s_dy] = True


while not division:
    visited = [[False] * M for _ in range(N)]

    cnt = 0
    for i in range(N):
        for j in range(M):
            if arr[i][j] > 0 and not visited[i][j]:
                bfs(i, j)
                cnt += 1
    if cnt > 1:
        divition = True
        print(answer)
        exit(0)

    if cnt < 1:
        print(0)
        exit(0)

    answer += 1

  • 시간초과가 났다.

 

 

[나의 풀이-두번째(성공)]

import sys
from collections import deque, defaultdict
input = sys.stdin.readline

N, M = map(int, input().split())
arr = [list(map(int, input().split())) for _ in range(N)]
dx, dy = [-1, 1, 0, 0], [0, 0, -1, 1]
answer = 0


def bfs(x, y):
    ice = defaultdict(int)
    global arr
    global visited
    dq = deque()
    dq.append((x, y))
    visited[x][y] = True
    while dq:
        p_x, p_y = dq.popleft()
        for index in range(4):
            s_dx, s_dy = p_x+dx[index], p_y+dy[index]

            if 0 <= s_dx < N and 0 <= s_dy < M:
                if arr[s_dx][s_dy] == 0:
                    ice[(p_x, p_y)] += 1

                if arr[s_dx][s_dy] > 0 and not visited[s_dx][s_dy]:
                    dq.append((s_dx, s_dy))
                    visited[s_dx][s_dy] = True
    return ice


while True:
    visited = [[False] * M for _ in range(N)]
    cnt = 0
    for i in range(N):
        for j in range(M):
            if arr[i][j] > 0 and not visited[i][j]:
                ice = bfs(i, j)
                cnt += 1
    if cnt > 1:
        print(answer)
        sys.exit()

    if cnt < 1:
        print(0)
        sys.exit()

    for (x, y), count in ice.items():
        arr[x][y] = 0 if arr[x][y] < count else arr[x][y] - count

    answer += 1
  • defaultdict를 사용하여 현재 위치 기준 주변의 0의 값 갯수를 쉽게 구할 수 있었다.
  • 0의 갯수가 현재 위치 값 보다 크다면 0으로, 아니면 현재위치 값 - 0의갯수로 arr리스트를 변경해주었다.
  • 이중 for문을 한번만 돌려 확인하는게 아니라 빙산이 나눠질때까지 해야하기 때문에 while문 안에서 이중 for문을 돌렸다.
  • 그리고 한번 while문이 돌 때마다 visited를 새로 초기화 해 줘야 한다.

 

 

[다른 사람의 풀이]

import sys
from collections import deque
input = sys.stdin.readline
N, M = map(int, input().split())
graph = [list(map(int, input().split()))  for _ in range(N)]
check = [ [-1]*M for _ in range(N)]
dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]
def bfs(start, current, nodes):
    y, x = start
    count = 0
    for k in range(4):
        b, a = (y + dy[k], x + dx[k])
        if (0 <= b <= N - 1) and (0 <= a <= M - 1) and (graph[b][a]==0):
            count += 1
    dq = deque()
    dq.append((y,x,count))
    check[start[0]][start[1]] = current
    nodes.remove((y, x))
    while dq:
        y, x, c = dq.popleft()
        for k in range(4):
            b, a = (y+dy[k], x+dx[k])
            count = 0
            if (0<=b<=N-1) and (0<=a<=M-1):
                for i in range(4):
                    u, v = b+dy[i], a+dx[i]
                    if (0 <= u <= N - 1) and (0 <= v <= M - 1) and (graph[u][v] == 0):
                        count += 1
                if (check[b][a]==current-1) and (graph[b][a]!=0):
                    dq.append((b, a, count))
                    nodes.remove((b, a))
                    check[b][a] += 1
        graph[y][x] = max(graph[y][x]-c, 0)
def sol():
    current = 0
    while True:
        nodes = [(i,j) for i in range(N) for j in range(M) if graph[i][j]!=0]
        if not nodes:
            return 0
        bfs(nodes[0], current, nodes)
        current += 1
        if nodes:
            return current-1
print(sol())

 

import sys
from collections import deque
input = sys.stdin.readline
N,M = map(int,input().split())
graph = [ list(map(int,input().split())) for _ in range(N) ]
dx=[-1,1,0,0]
dy=[0,0,-1,1]
def bfs(x,y,visited):
    queue = deque()
    queue.append((x,y))
    melt = deque()
    visited[x][y]=1
    while queue:
        x,y = queue.popleft()
        mcnt=0
        for i in range(4):
            nx = x+dx[i]
            ny = y+dy[i]
            if nx <0 or nx>=N or ny<0 or ny >= M:continue
            if graph[nx][ny] == 0:mcnt+=1;continue
            if graph[nx][ny] != 0 and visited[nx][ny]==0:
                visited[nx][ny] = 1
                queue.append((nx,ny))
        if mcnt:melt.append((x,y,mcnt))
    return melt
cnt=0
while(True):
    area=0
    visited = [[0]* M for _ in range(N)]
    for i in range(N-1):
        for j in range(M-1):
            if graph[i][j] !=0 and visited[i][j]==0:
                area+=1
                melt=bfs(i,j,visited)
                while melt:
                    mx,my,mc=melt.popleft()
                    graph[mx][my]=max(graph[mx][my]-mc,0)
    if area==0:cnt=0;break
    if area>=2:break
    cnt+=1
print(cnt)

'알고리즘 > 알고리즘 문제' 카테고리의 다른 글

[python] 백준15686 > 부루트포스 > 치킨 배달  (0) 2021.02.01
[python] 백준 > 부루트포스 > 백설 공주와 일곱 난쟁이  (0) 2021.01.29
[python] 백준 > 다익스트라 > 파티  (0) 2021.01.27
[python] 백준 > 덱  (0) 2021.01.26
[python] 백준 > 다익스트라 > 최소비용 구하기  (0) 2021.01.26
    '알고리즘/알고리즘 문제' 카테고리의 다른 글
    • [python] 백준15686 > 부루트포스 > 치킨 배달
    • [python] 백준 > 부루트포스 > 백설 공주와 일곱 난쟁이
    • [python] 백준 > 다익스트라 > 파티
    • [python] 백준 > 덱
    happyso
    happyso

    티스토리툴바