코드
import sys
sys.setrecursionlimit(10**6)
input = sys.stdin.readline
def dfs(x, y, graph, check):
if (0 <= x < n) and (0 <= y < m) and (graph[x][y] == '1') and (not check[x][y]):
check[x][y] = True
dfs(x+1, y, graph, check)
dfs(x-1, y, graph, check)
dfs(x, y+1, graph, check)
dfs(x, y-1, graph, check)
case = int(input())
for _ in range(case):
count = 0
m, n, k = map(int, input().split())
field = [[0] * m for _ in range(n)]
visited = [[False] * m for _ in range(n)]
for _ in range(k):
x, y = map(int, input().split())
field[y][x] = '1'
for i in range(n):
for j in range(m):
if field[i][j] == "1" and (not visited[i][j]):
count += 1
dfs(i,j,field,visited)
print(count)
'백준' 카테고리의 다른 글
[백준] 10026번 적록색약 파이썬 코드 (0) | 2023.09.14 |
---|---|
[백준] 2667번 단지번호붙이기 파이썬 코드 (0) | 2023.09.14 |
[백준] 4963번 섬의 개수 파이썬 코드 (0) | 2023.09.14 |
[백준] 14716번 현수막 파이썬 코드 (0) | 2023.09.14 |
[백준] 13565번 침투 파이썬 코드 (0) | 2023.09.14 |
코드
import sys
sys.setrecursionlimit(10**6)
input = sys.stdin.readline
def dfs(x, y, graph, check):
if (0 <= x < n) and (0 <= y < m) and (graph[x][y] == '1') and (not check[x][y]):
check[x][y] = True
dfs(x+1, y, graph, check)
dfs(x-1, y, graph, check)
dfs(x, y+1, graph, check)
dfs(x, y-1, graph, check)
case = int(input())
for _ in range(case):
count = 0
m, n, k = map(int, input().split())
field = [[0] * m for _ in range(n)]
visited = [[False] * m for _ in range(n)]
for _ in range(k):
x, y = map(int, input().split())
field[y][x] = '1'
for i in range(n):
for j in range(m):
if field[i][j] == "1" and (not visited[i][j]):
count += 1
dfs(i,j,field,visited)
print(count)
'백준' 카테고리의 다른 글
[백준] 10026번 적록색약 파이썬 코드 (0) | 2023.09.14 |
---|---|
[백준] 2667번 단지번호붙이기 파이썬 코드 (0) | 2023.09.14 |
[백준] 4963번 섬의 개수 파이썬 코드 (0) | 2023.09.14 |
[백준] 14716번 현수막 파이썬 코드 (0) | 2023.09.14 |
[백준] 13565번 침투 파이썬 코드 (0) | 2023.09.14 |