Algorithms
[Baekjoon] 1926. ๊ทธ๋ฆผ - python
thals0
2023. 10. 3. 10:01
728x90
https://www.acmicpc.net/problem/1926
1926๋ฒ: ๊ทธ๋ฆผ
์ด๋ค ํฐ ๋ํ์ง์ ๊ทธ๋ฆผ์ด ๊ทธ๋ ค์ ธ ์์ ๋, ๊ทธ ๊ทธ๋ฆผ์ ๊ฐ์์, ๊ทธ ๊ทธ๋ฆผ ์ค ๋์ด๊ฐ ๊ฐ์ฅ ๋์ ๊ฒ์ ๋์ด๋ฅผ ์ถ๋ ฅํ์ฌ๋ผ. ๋จ, ๊ทธ๋ฆผ์ด๋ผ๋ ๊ฒ์ 1๋ก ์ฐ๊ฒฐ๋ ๊ฒ์ ํ ๊ทธ๋ฆผ์ด๋ผ๊ณ ์ ์ํ์. ๊ฐ๋ก๋ ์ธ๋ก
www.acmicpc.net
๋ฌธ์ ์ ๋ณด
๋ฌธ์ ์ ํ | ๋์ด๋ | ๊ฑธ๋ฆฐ ์๊ฐ | ํด๊ฒฐ ์ ๋ฌด | ์ค์ค๋ก ๊ตฌํ ์ฑ๊ณต |
BFS | ์ค๋ฒ1 | 45m | O | O |
์ค๊ณ ๋ฐฉ๋ฒ
BFS
์ฝ๋
import sys
from collections import deque
input = sys.stdin.readline
n, m = map(int, input().split())
graph = []
for i in range(n):
graph.append(list(map(int, input().split())))
arr = []
visited = [[0]*m for _ in range(n)]
dx = [1,0,-1,0]
dy = [0,1,0,-1]
def bfs(i,j):
q = deque()
q.append((i,j))
visited[i][j] = 1
cnt = 0
while q:
x, y = q.popleft()
# q์์ popleftํ ๋๋ง๋ค cntํ๋ฉด, ๋์ด ๊ตฌํ ์ ์์
cnt += 1
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 visited[nx][ny] == 0 and graph[nx][ny] == 1:
visited[nx][ny] = 1
q.append((nx, ny))
return cnt
for i in range(n):
for j in range(m):
# graph[i][j] == 1 ์ด๋ฉด์, ๋ฐฉ๋ฌธํ์ง ์์ ์นธ์์๋ง bfs ์คํ
if graph[i][j] == 1 and visited[i][j] == 0:
arr.append(bfs(i,j))
print(len(arr))
# len(arr) == 0์ด๋ฉด "ValueError: max() arg is an empty sequence" ๋ฐ์
if len(arr) == 0:
print(0)
else:
print(max(arr))
์๊ฐ ๋ณต์ก๋
O(N)
์ด๋ ค์ ๋ ์
- https://www.acmicpc.net/problem/2178 ์ด ๋ฌธ์ ์ ๊ฐ์ด ์ต๋จ ๊ฒฝ๋ก๋ฅผ ๊ตฌํ๋ ๋ฌธ์ ์์๋ graph[nx][ny] = graph[x][y] + 1ํด์ฃผ๋ฉด ๋๋๋ฐ ๋์ด๋ฅผ ๊ตฌํ ๋๋ q์์ pop์ ํ ๋งํผ ๋ํด์ฃผ์ด์ผ ํจ
- len(arr) == 0์ด๋ฉด max(arr)์ "ValueError: max() arg is an empty sequence" ๋ฐ์
728x90