๐ฉ๐ปโ๐ป๋ฌธ์ ๋งํฌ
[๋ฐฑ์ค 1012] ์ ๊ธฐ๋ ๋ฐฐ์ถ (Python)
โ๏ธIdea Sketch
2021-08-02
1. ๋จ์ง๋ฒํธ๋ถ์ด๊ธฐ์ ๊ฐ์ DFS ๋ก์ง
2. ์ค๋๋ง์ ํ์ด์ ์์ ๊ฒ
- main์์ dfs()๋ฅผ ํธ์ถํ ๋
- ์ด์ค๋ฐ๋ณต๋ฌธ์ ์ฌ์ฉํด์
- 2์ฐจ์ ๋ฐฐ์ด graph ์ ๋ชจ๋ ์์๋ฅผ ํ์ธํ๋ค
3. dx dy ์ฌ์ฉ ์ ์์์๊ฐ 4ms ์ฆ๊ฐ (96ms)
dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]
def dfs(x, y):
if (0<=x<n) and (0<=y<m):
if graph[x][y] == 1:
graph[x][y] = -1
for i in range(4):
dfs(x+dx[i], y+dy[i])
return True
return False
โ๏ธ์์ค์ฝ๋
2021-08-02 92ms ํต๊ณผ
import sys
sys.setrecursionlimit(10**6)
def dfs(x, y):
if (0<=x<n) and (0<=y<m):
if graph[x][y] == 1:
graph[x][y] = -1
dfs(x-1, y)
dfs(x+1, y)
dfs(x, y+1)
dfs(x, y-1)
return True
return False
if __name__ == "__main__":
t = int(input())
for _ in range(t):
n, m, k = map(int, input().split())
graph = [[0 for _ in range(m)] for _ in range(n)]
for _ in range(k):
x, y = map(int, sys.stdin.readline().rstrip().split())
graph[x][y] = 1
cnt = 0
for i in range(n):
for j in range(m):
if dfs(i, j) == True:
cnt += 1
print(cnt)