๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

๐Ÿ’ปAlgorithm/PS

[2017 ์นด์นด์˜ค์ฝ”๋“œ ์˜ˆ์„ ] ์ปฌ๋Ÿฌ๋ง๋ถ - ํŒŒ์ด์ฌ

๋ฌธ์ œ

https://programmers.co.kr/learn/courses/30/lessons/1829

 

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - ์นด์นด์˜คํ”„๋ Œ์ฆˆ ์ปฌ๋Ÿฌ๋ง๋ถ

6 4 [[1, 1, 1, 0], [1, 2, 2, 0], [1, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 3], [0, 0, 0, 3]] [4, 5]

programmers.co.kr

์˜์—ญ์˜ ์ˆ˜์™€ ๊ฐ€์žฅ ํฐ ์˜์—ญ์˜ ๋„“์ด๋ฅผ ๊ตฌํ•˜๋Š” ๋ฌธ์ œ์ด๋‹ค.

 

๋ฌธ์ œํ’€์ด

ํ”ํžˆ ๋ณผ ์ˆ˜ ์žˆ๋Š” bfs ๋ฌธ์ œ์™€ ์œ ์‚ฌํ•˜๋‹ค.

que์— ์ขŒํ‘œ๋ฅผ ๋„ฃ๊ณ  que๊ฐ€ ๋นŒ ๋•Œ๊นŒ์ง€ move๋ฅผ ์ด์šฉํ•ด ์ฃผ์œ„ ์ขŒํ‘œ(์ƒ,ํ•˜,์ขŒ,์šฐ)๋ฅผ ํƒ์ƒ‰ํ•˜๊ณ , ๋™์ผํ•œ ๊ฐ’์„ ์ง€๋‹Œ ์ขŒํ‘œ๋Š” que์— ์ถ”๊ฐ€ํ•ด์ฃผ๋Š” ๋ฐฉ์‹์œผ๋กœ ํƒ์ƒ‰์„ ์ง„ํ–‰ํ•œ๋‹ค. ํ•ด๋‹น ์ขŒํ‘œ๋ฅผ ๋ฐฉ๋ฌธํ–ˆ๋‹ค๋ฉด check ๊ฐ’์„ ๋ฐ”๊ฟ”์ฃผ์–ด ๋ฐฉ๋ฌธ ์ฒดํฌ๋ฅผ ํ•ด์ค€๋‹ค.

 

bfs๋ฅผ ์ƒˆ๋กœ ์‹คํ–‰ํ•  ๋•Œ ๋งˆ๋‹ค ์ƒˆ๋กœ์šด ์˜์—ญ์„ ํƒ์ƒ‰ํ•˜๋Š” ๊ฒƒ์ด๋ฏ€๋กœ ์˜์—ญ ๊ฐ’(answer[0])์— 1์„ ๋”ํ•ด์ฃผ๊ณ ,

bfs๋ฅผ return ํ•˜๊ธฐ ์ „์— ๊ธฐ์กด์˜ ๊ฐ€์žฅ ํฐ ์˜์—ญ ๊ฐ’(answer[1])๊ณผ ๋น„๊ตํ•˜์—ฌ ๊ฐ’์„ ๊ฐฑ์‹ ํ•ด์ค€๋‹ค.

 

 

์ฝ”๋“œ

import sys
from collections import deque

def bfs(x,y,answer):
	que=[(x,y)]
	temp=picture[x][y]
	move=[[1,0],[-1,0],[0,1],[0,-1]]
	count=1
	check[x][y] =1
	while que:
		x,y=que.pop()
		for i in move:
			dx=x+i[0]
			dy=y+i[1]
			if 0<=dx<m and 0<=dy<n:
				if temp==picture[dx][dy] and not check[dx][dy]: ##์ƒ‰์ด ๊ฐ™์œผ๋ฉด์„œ ๋ฐฉ๋ฌธํ•˜์ง€ ์•Š์€ ๊ฒฝ์šฐ
					count+=1
					check[dx][dy]=1
					que.append((dx,dy))
					
	answer[0]+=1
	answer[1]=max(answer[1],count)
	return 

def solution(m, n, picture):
	answer = [0,0]
	for i in range(m):
		for j in range(n):
			if check[i][j]==0 and picture[i][j]!=0:
				bfs(i,j,answer) #์ƒˆ๋กœ์šด ์˜์—ญ ํƒ์ƒ‰
	return answer
    
if __name__ == "__main__":
    input = sys.stdin.readline
    m, n = map(int, input().split())
    picture = [list(map(int, input().split())) for _ in range(m)]
    check = [[0] * n for _ in range(m)]
    number_of_area, max_size_of_one_area = solution(m, n, picture)
    print(number_of_area, max_size_of_one_area)