DFS/BFS
μ¬μ― λ²μ§Έ λ¬Έμ !
def dfs(x, y):
if x < 0 or x >= N or y < 0 or y >= N:
return 0
if visit[x][y] == 0 and graph[x][y] > i:
visit[x][y] = 1
dfs(x+1, y)
dfs(x-1, y)
dfs(x, y+1)
dfs(x, y-1)
return 1
return 0
N = int(input())
graph, Hindex, result = list(), set(), list()
for _ in range(N):
_input = list(map(int, input().split()))
Hindex.update(_input)
graph.append(_input)
for i in Hindex:
visit, num = [[0 for _ in range(N)] for _ in range(N)], 0
for x in range(N):
for y in range(N):
if visit[x][y] == 0 and graph[x][y] > i:
num += dfs(x, y)
result.append(num)
print(max(result))
μκ° μ νμ΄ 1μ΄μ΄κΈ° λλ¬Έμ μ
λ ₯λ μ§ν λμ΄λ₯Ό μ€λ³΅ μμ΄ μ μ₯νκ³ μ μ₯λ λμ΄λ§ νμνλ € νλ€. Hindex
λΌλ set
λ₯Ό λ§λ€κ³ μ μ₯νλ€.
μ΄ λΆλΆμ΄ λ¬Έμ μλ€. μ μ κΈ°λ κ²½μ°κ° μλ€λ κ±Έ κ³ λ €νμ§ μμ κ±°λ€.
μ μ½λλ λ°νμ μλ¬ (RecursionError)
κ° λ΄λ€.
python
μμ μ¬κ· depth
λ 3000μΈλ° μ΄κ±Έ κ³ λ €νμ§ λͺ»νλ€.
N <= 100
μ΄λ―λ‘ depth
λ 10000
μ ν¨μ¬ λλλ€.
def dfs(x, y):
if x < 0 or x >= N or y < 0 or y >= N:
return 0
if visit[x][y] == 0 and graph[x][y] > i:
visit[x][y] = 1
dfs(x+1, y)
dfs(x-1, y)
dfs(x, y+1)
dfs(x, y-1)
return 1
return 0
N = int(input())
graph, result = list(), list()
for _ in range(N):
_input = list(map(int, input().split()))
graph.append(_input)
for i in range(2, 101):
visit, num = [[0 for _ in range(N)] for _ in range(N)], 0
for x in range(N):
for y in range(N):
if visit[x][y] == 0 and graph[x][y] > i:
num += dfs(x, y)
result.append(num)
print(max(result))
μ μ½λλ λ¨μν Hindex
λ§ μμ ν μ½λμ΄λ€.
μ΄ μ½λλ λ¬Έμ κ° μλλ°, for
μ λ²μκ° (2,101)
μ΄λ€. 0
λΆν° νμν΄μΌ νλλ°,,,
import sys
sys.setrecursionlimit(100000)
def dfs(x, y):
if x < 0 or x >= N or y < 0 or y >= N:
return 0
if visit[x][y] == 0 and graph[x][y] > i:
visit[x][y] = 1
dfs(x+1, y)
dfs(x-1, y)
dfs(x, y+1)
dfs(x, y-1)
return 1
return 0
N = int(input())
graph, result = list(), list()
for _ in range(N):
_input = list(map(int, input().split()))
graph.append(_input)
for i in range(0, 101):
visit, num = [[0 for _ in range(N)] for _ in range(N)], 0
for x in range(N):
for y in range(N):
if visit[x][y] == 0 and graph[x][y] > i:
num += dfs(x, y)
result.append(num)
print(max(result))
맨 μμ sys.setrecursionlimit(100000)
λ μ¬κ· depth
λ₯Ό μμλ‘ λλ €μ€ κ²μ΄λ€.
for
μ λ²μ μμ (0, 101)
λ‘ μμ νλ€.
κ²°κ³Όλ,,, λ§μμ΅λλ€!!
.
.
.
μμΌλ‘ λ²μλ₯Ό κ³ λ €ν΄μ dfs
λ₯Ό μ¨μΌκ² μ΅λλ€.π
λ²μκ° ν¬λ©΄, dfs
λ₯Ό for
λ‘ κ΅¬ννκ±°λ, bfs
λ₯Ό μ¬μ©ν΄μΌκ² μ΅λλ€.