<그림 1>과 같이 정사각형 모양의 지도가 있다. 1은 집이 있는 곳을, 0은 집이 없는 곳을 나타낸다. 철수는 이 지도를 가지고 연결된 집의 모임인 단지를 정의하고, 단지에 번호를 붙이려 한다. 여기서 연결되었다는 것은 어떤 집이 좌우, 혹은 아래위로 다른 집이 있는 경우를 말한다. 대각선상에 집이 있는 경우는 연결된 것이 아니다. <그림 2>는 <그림 1>을 단지별로 번호를 붙인 것이다. 지도를 입력하여 단지수를 출력하고, 각 단지에 속하는 집의 수를 오름차순으로 정렬하여 출력하는 프로그램을 작성하시오.
![](https://blog.kakaocdn.net/dn/bx1Nv6/btrxoVFnrOJ/2Q93LdXbeLAiFV8e0Jgkf0/img.png)
입력
첫 번째 줄에는 지도의 크기 N(정사각형이므로 가로와 세로의 크기는 같으며 5≤N≤25)이 입력되고, 그 다음 N줄에는 각각 N개의 자료(0혹은 1)가 입력된다.
출력
첫 번째 줄에는 총 단지수를 출력하시오. 그리고 각 단지내 집의 수를 오름차순으로 정렬하여 한 줄에 하나씩 출력하시오.
예제 입력 1 복사
7
0110100
0110101
1110101
0000111
0100000
0111110
0111000
예제 출력 1 복사
3
7
8
9
문제풀이
문제해결
프로그래머스등에서 global 쓸때는 해당함수, solution() 함수 둘다 global 선언해줘야함!!
DFS버전
def DFS(current_x, current_y, map_data) :
global count
global n
dx = [-1, 0, 1, 0] #top, right, bottom, light
dy = [0, 1, 0, -1]
count += 1
#이미 방문한 곳은 재방문 하지 않기 위해 0처리
map_data[current_x][current_y] = 0 #DFS 다 끝나면 해당 구역은 다 0처리됨
for i in range(4) :
next_x = current_x + dx[i]
next_y = current_y + dy[i]
if 0 <= next_x < n and 0 <= next_y < n and map_data[next_x][next_y] == 1:
DFS(next_x, next_y, map_data)
def solution() :
global n
global count
n = int(input())
maps = []
result = []
for i in range(n) : #map 입력 받기
m = input()
temp = []
for j in m :
temp.append(int(j))
maps.append(temp)
#완전 탐색 하면서 1 있는 곳은 DFS 시작
for i in range(n) :
for j in range(n) :
if maps[i][j] == 1 :
count = 0
DFS(i, j, maps)
result.append(count)
print(len(result))
result.sort()
for i in result :
print(i)
solution()
BFS 버전 - global로 카운트
from collections import deque
def BFS(start_x, start_y, map_data) :
global count
global n
dx = [-1, 0, 1, 0] #top 0, right 1, bottom 2, light 3
dy = [0, 1, 0, -1]
dq = deque() #BFS를 위한 큐 생성
count += 1
dq.append((start_x, start_y)) #1. 큐에 시작점 추가
map_data[start_x][start_y] = 0 #2. 큐에 넣은 시작점은 방문처리
while dq :
now_idx = dq.popleft() #현재 방문 노드
for i in range(4) : #4방향 이동(top-> right-> bottom-> light)
next_x = now_idx[0] + dx[i] #큐에 들어간 좌표 중 연결된 다음 x좌표[0]
next_y = now_idx[1] + dy[i] #큐에 들어간 좌표 중 연결된 다음 y좌표[1]
#x좌표 내 and y좌표 내에서 이동 and 인접한 다음 방문할 곳이 길(1)인 경우 이동
if 0 <= next_x <= (n-1) and 0 <= next_y <= (n-1) and map_data[next_x][next_y] == 1:
count += 1
map_data[next_x][next_y] = 0 #방문한 곳은 벽(0)처리
dq.append((next_x, next_y))
def solution() :
global n
global count
n = int(input())
maps = []
result = []
for i in range(n) : #map 입력 받기
m = input()
temp = []
for j in m :
temp.append(int(j))
maps.append(temp)
#완전 탐색 하면서 1 있는 곳은 BFS() 시작
for i in range(n) :
for j in range(n) :
if maps[i][j] == 1 :
count = 0
BFS(i, j, maps)
result.append(count)
print(len(result))
result.sort()
for i in result :
print(i)
solution()
BFS 글로벌 안쓰고 return으로 반환
from collections import deque
def BFS(start_x, start_y, map_data, count, n) :
dx = [-1, 0, 1, 0] #top 0, right 1, bottom 2, light 3
dy = [0, 1, 0, -1]
dq = deque() #BFS를 위한 큐 생성
count += 1
dq.append((start_x, start_y)) #1. 큐에 시작점 추가
map_data[start_x][start_y] = 0 #2. 큐에 넣은 시작점은 방문처리
while dq :
now_idx = dq.popleft() #현재 방문 노드
for i in range(4) : #4방향 이동(top-> right-> bottom-> light)
next_x = now_idx[0] + dx[i] #큐에 들어간 좌표 중 연결된 다음 x좌표[0]
next_y = now_idx[1] + dy[i] #큐에 들어간 좌표 중 연결된 다음 y좌표[1]
#x좌표 내 and y좌표 내에서 이동 and 인접한 다음 방문할 곳이 길(1)인 경우 이동
if 0 <= next_x <= (n-1) and 0 <= next_y <= (n-1) and map_data[next_x][next_y] == 1:
count += 1
map_data[next_x][next_y] = 0 #방문한 곳은 벽(0)처리
dq.append((next_x, next_y))
return count
def solution() :
n = int(input())
maps = []
result = []
for i in range(n) : #map 입력 받기
m = input()
temp = []
for j in m :
temp.append(int(j))
maps.append(temp)
#완전 탐색 하면서 1 있는 곳은 BFS() 시작
for i in range(n) :
for j in range(n) :
if maps[i][j] == 1 :
count = 0
count = BFS(i, j, maps, count, n)
result.append(count)
print(len(result))
result.sort()
for i in result :
print(i)
solution()
'코테풀이 > DFS' 카테고리의 다른 글
[인프런 | DFS] 사다리타기(이차원 리스트 밑에서부터 이동) (0) | 2022.04.16 |
---|---|
[백준 | 실버1] 2468번: 안전 영역(DFS, 떨어진 영역 카운트) (0) | 2022.04.15 |
[인프런 | 파이썬 알고리즘] 등산경로(DFS, 높은곳만 이동, 출발지-목적지) (0) | 2022.04.04 |
[인프런 | 파이썬 알고리즘] 섬나라 아일랜드(DFS, BFS, 8방향 좌표 이동) (0) | 2022.03.28 |
[백준 | 실버2] 1260번: DFS와 BFS (0) | 2022.01.24 |
[백준 | 실버1] 2667번: 단지번호붙이기(DFS, BFS, 떨어져 있는 이차원리스트)