[BaekJoon] 2589๋ฒˆ : ๋ณด๋ฌผ์„ฌ

Updated:

2589๋ฒˆ : ๋ณด๋ฌผ์„ฌ


์ฒ˜์Œ์—๋Š” ํŠธ๋ฆฌ์˜ ์ง€๋ฆ„์„ ๊ตฌํ•˜๋Š” ๋ฌธ์ œ์ธ ์ค„ ์•Œ๊ณ  ํŠธ๋ฆฌ์˜ ์ง€๋ฆ„์„ ๊ตฌํ–ˆ์œผ๋‚˜ ํ‹€๋ ธ์Šต๋‹ˆ๋‹ค๋ฅผ ๋ฐ›์•˜๋‹ค.

๋„ˆ๋ฌด ๋ฐ”๋ณด๊ฐ™์€ ์ƒ๊ฐ์ด์—ˆ๋‹ค! ๋ฌธ์ œ์—์„œ ์ฃผ์–ด์ง„ ์˜ˆ์‹œ๋งŒ ๋ณด๊ณ  ํŠธ๋ฆฌ์˜ ์ง€๋ฆ„์„ ๊ตฌํ•˜๋ ค๊ณ  ํ•˜๋‹ค๋‹ˆ..

์•„์ฃผ ๊ฐ„๋‹จํ•œ ์˜ˆ๋กœ ์œ„ ์˜ˆ์‹œ์˜ [2, 6] ์„ L ๋กœ ๋ฐ”๊พธ์–ด์ฃผ๋ฉด ํŠธ๋ฆฌ๊ฐ€ ์•„๋‹ˆ๋ผ ๊ทธ๋ž˜ํ”„๊ฐ€ ๋œ๋‹ค.

๊ฒฐ๊ตญ ๋ชจ๋“  ๋•…์—์„œ BFS ๋ฅผ ์ˆ˜ํ–‰ํ•ด ๊ฐ€์žฅ ๋ฉ€๋ฆฌ ๋–จ์–ด์ ธ์žˆ๋Š” ๋•…๊ณผ์˜ ๊ฑฐ๋ฆฌ๋ฅผ ์ถœ๋ ฅํ•˜๋ฉด ๋œ๋‹ค.


from collections import deque


def BFS(start):
	queue = deque([start])
	visit = [[0] * m for _ in range(n)]
	visit[start[0]][start[1]] = 1
	dirs = [[-1, 0], [0, 1], [1, 0], [0, -1]]
	distance = 0

	while queue:
		cur_i, cur_j, weight = queue.popleft()
		distance = weight
		for val in dirs:
			visit_i = cur_i + val[0]
			visit_j = cur_j + val[1]
			if 0 <= visit_i < n and 0 <= visit_j < m and visit[visit_i][visit_j] == 0:
				if ground[visit_i][visit_j] == 'L':
					visit[visit_i][visit_j] = 1
					queue.append([visit_i, visit_j, weight + 1])

	return distance


def solution():
	output = 0

	for i in range(n):
		for j in range(m):
			if ground[i][j] == 'L':
				result = BFS([i, j, 0])
				if output < result:
					output = result

	return output


if __name__ == '__main__':
	n, m = map(int, input().rsplit())
	ground = [list(map(str, input())) for _ in range(n)]

	print(solution())



Categories:

Updated:

Leave a comment