๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
  • What would life be If we had no courage to attemp anything?
Problem Solving/BAEKJOON

[baekjoon]python #2636 ์น˜์ฆˆ

by DevIseo 2022. 5. 10.

https://www.acmicpc.net/problem/2636

 

2636๋ฒˆ: ์น˜์ฆˆ

์•„๋ž˜ <๊ทธ๋ฆผ 1>๊ณผ ๊ฐ™์ด ์ •์‚ฌ๊ฐํ˜• ์นธ๋“ค๋กœ ์ด๋ฃจ์–ด์ง„ ์‚ฌ๊ฐํ˜• ๋ชจ์–‘์˜ ํŒ์ด ์žˆ๊ณ , ๊ทธ ์œ„์— ์–‡์€ ์น˜์ฆˆ(ํšŒ์ƒ‰์œผ๋กœ ํ‘œ์‹œ๋œ ๋ถ€๋ถ„)๊ฐ€ ๋†“์—ฌ ์žˆ๋‹ค. ํŒ์˜ ๊ฐ€์žฅ์ž๋ฆฌ(<๊ทธ๋ฆผ 1>์—์„œ ๋„ค๋ชจ ์นธ์— X์นœ ๋ถ€๋ถ„)์—๋Š” ์น˜์ฆˆ๊ฐ€ ๋†“

www.acmicpc.net

from collections import deque
col,row = map(int,input().split())
arr=[list(map(int,input().split())) for _ in range(col)]

def bfs(y,x):
    q = deque()
    q.append((y,x))
    visit=[[0]*row for _ in range(col)]
    visit[y][x]=1

    while q:
        ny,nx= q.popleft()
        directy = [-1,1,0,0]
        directx = [0,0,-1,1]

        for i in range(4):
            dy = directy[i] + ny
            dx = directx[i] + nx

            if 0<=dy<col and 0<=dx<row:
                if visit[dy][dx] == 0:
                	#์น˜์ฆˆ๊ฐ€ ์žˆ๋‹ค๋ฉด...
                    if arr[dy][dx]==1:
                        visit[dy][dx]=1
                        #์น˜์ฆˆ ๋…น์ด๊ธฐ!
                        arr[dy][dx]=0
                        continue
                    #์น˜์ฆˆ๊ฐ€ ์—†๋‹ค๋ฉด...
                    if arr[dy][dx]==0:
                        visit[dy][dx]=1
                        q.append((dy,dx))

#์น˜์ฆˆ์˜ ๊ฐœ์ˆ˜๋ฅผ ์„ธ์–ด๋ณด์ž!
def count_cheeses():
    cnt_cheese=0
    for i in range(col):
        for j in range(row):
            if arr[i][j]==1:
                cnt_cheese+=1
    return cnt_cheese


time=0 #์น˜์ฆˆ๊ฐ€ ๋‹ค ๋…น๋Š” ์‹œ๊ฐ„
last_cheeses=0 #๋งˆ์ง€๋ง‰ ์น˜์ฆˆ

while True:
	#์น˜์ฆˆ์˜ ๊ฐœ์ˆ˜๋ฅผ ์„ธ๋Ÿฌ ๊ฐ€๊ธฐ!
    cnt = count_cheeses()
    #์น˜์ฆˆ๊ฐ€ ์žˆ๋‹ค๋ฉด!
    if cnt>0:
        bfs(0,0) #bfs์‹œ์ž‘!
        last_cheeses=cnt #์น˜์ฆˆ์˜ ๊ฐฏ์ˆ˜ ๊ฐฑ์‹ 
        time+=1 #์น˜์ฆˆ ๋…น๋Š” ์‹œ๊ฐ„ +1
        
    #์น˜์ฆˆ๊ฐ€ ์—†๋‹ค๋ฉด!
    elif cnt==0:
    	#while๋ฌธ ๋ฉˆ์ถฐ!
        break

#์ถœ๋ ฅํ•˜๊ธฐ
print(time)
print(last_cheeses)

๋Œ“๊ธ€