๋ฌธ์
https://www.acmicpc.net/problem/2589
ํ์ด
Python3 ์์ ์ฌ์ฉํ ํ์ด
# ๋ฐฑ์ค 2589๋ฒ ๋ฌธ์ -๋ณด๋ฌผ ํ์
from collections import deque
n, m = map(int, input().split())
dx, dy = [0,0,-1,1], [1,-1,0,0]
graph = [list(map(str, input())) for _ in range(n)]
def bfs(x,y):
q = deque()
q.append((x, y))
cnt = 0
visited = [[0]*m for _ in range(n)]
visited[x][y] = 1
while q:
x, y = q.popleft()
for i in range(4):
nx = x + dx[i]
ny = y + dy[i]
if 0 <= nx < n and 0 <= ny < m and not visited[nx][ny] and graph[nx][ny] == 'L':
visited[nx][ny] = visited[x][y] + 1
cnt = max(cnt, visited[nx][ny])
q.append((nx, ny))
return cnt - 1
result = 0
for i in range(n):
for j in range(m):
if graph[i][j] == 'L':
# ๊ฐ์ฅ์๋ฆฌ๊ฐ ์๋
if i>0 and i+1<n:
if graph[i-1][j] == "L" and graph[i+1][j] == "L":
continue
if j>0 and j+1<m:
if graph[i][j-1] == "L" and graph[i][j+1] == "L":
continue
result = max(result, bfs(i,j))
print(result)
์ด ํ์ด๋ ๋ฐฑํธ๋ํน๊ณผ BFS๋ฅผ ์ฌ์ฉํ์ฌ ๋ฌธ์ ๋ฅผ ํ์ด์ฃผ์๋ค.
์ฒ์์๋ ๋ฐฑํธ๋ํน์ ์ฌ์ฉํ์ง ์์์ pypy3์์๋ง ํต๊ณผ๊ฐ ๋์๋ค.
L์ ํ์ํ ๋ ๊ฐ์ฅ์๋ฆฌ ์ธ์ง ํ์ธํด์ฃผ๋ ์ฝ๋๋ฅผ ์ถ๊ฐ ํ์๋๋ฐ 300ms ์ฐจ์ด๊ฐ ๋ฌ๋ค.
# ๊ฐ์ฅ์๋ฆฌ๊ฐ ์๋
if i>0 and i+1<n:
if graph[i-1][j] == "L" and graph[i+1][j] == "L":
continue
if j>0 and j+1<m:
if graph[i][j-1] == "L" and graph[i][j+1] == "L":
continue
์ด๋ฌํ ์ธ์ธํ ๋ถ๋ถ๋ค์ ์ ํ์ ํด์ผ ์ฝ๋ฉํ ์คํธ๋ฅผ ์ ํ๊ฒ ๋๋ ๊ฒ ๊ฐ๋ค.
'๐๏ธ Algorithm > ๐ฉ ๋ฐฑ์ค' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
๐ฉ [๋ฐฑ์ค] [Python] 24445๋ฒ_์๊ณ ๋ฆฌ์ฆ ์์ - ๋๋น ์ฐ์ ํ์ 2 (0) | 2022.12.16 |
---|---|
๐ฉ [๋ฐฑ์ค] [Python] 16234๋ฒ_์ธ๊ตฌ ์ด๋ (0) | 2022.12.16 |
๐ฉ [๋ฐฑ์ค] [Python] 3273๋ฒ_๋ ์์ ํฉ (0) | 2022.12.14 |
๐ฉ [๋ฐฑ์ค] [Python] [Class5] 2467๋ฒ_์ฉ์ก (0) | 2022.12.08 |
๐ฉ [๋ฐฑ์ค] [Python] 3184๋ฒ_์ (0) | 2022.12.07 |