https://n1tjrgns.tistory.com/245
[백준] 2667번 단지번호붙이기 Java (DFS, BFS)
그래프 관련 문제들의 유형이 다 비슷비슷 한 것 같아보인다. 확실히 짚고 넘어가야 할 필요를 느꼈다. 물론 돌아서면 까먹어서 문제.. 문제링크 과 같이 정사각형 모양의 지도가 있다. 1은 집이
n1tjrgns.tistory.com
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
public class Main {
static int N;
static int[][] xy;
static boolean[][] visit;
static int[] x_move = {-1,0,1,0};
static int[] y_move = {0,-1,0,1};
static int house_cnt = 0; //단지수
static int[] house = new int[25*25];
static StringBuilder sb = new StringBuilder();
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
N = Integer.parseInt(br.readLine());
xy = new int[N][N];
visit = new boolean[N][N];
for(int i = 0; i < N; i++) {
String str = br.readLine();
for(int j = 0; j < N; j++) {
xy[i][j] = str.charAt(j) - '0';
}
}
for(int i = 0; i < N; i++) {
for(int j = 0; j < N; j++) {
if(!visit[i][j] && xy[i][j] == 1) {
dp(i,j,3);
house_cnt++;
}
}
}
Arrays.sort(house);
System.out.println(house_cnt);
for(int i = 0; i < house.length; i++) {
if(house[i] != 0)
System.out.println(house[i]);
}
}
static void dp (int x, int y, int direction) {
visit[x][y] = true; //1일 때 dp로 들어오는 조건으로 이미 처리된 좌표이다
int dir = 0; //검사한 방향 수
house[house_cnt]++;
while(dir < 4) {
int tx = x+x_move[direction];
int ty = y+y_move[direction];
if(tx >= N || tx < 0 || ty >= N || ty < 0) {
direction = change(direction);
dir++; //이 방향은 막혀있다
continue; //새로운 좌표를 구해야함
}
if(xy[tx][ty] == 1 && visit[tx][ty] == false) { //새로운 집을 찾았다면
dp(tx,ty,direction);
}
else {
direction = change(direction); //방향을 바꿔준다
dir++;
}
}
}
static int change(int n) {
if(n <= 0) {
return 3;
}
else
return n-1;
}
}
'백준' 카테고리의 다른 글
[백준] 10814 나이순 정렬 (0) | 2021.11.28 |
---|---|
[백준] 2178 미로 탐색 (0) | 2021.11.28 |
[백준] 1697 숨바꼭질 (0) | 2021.11.25 |
[백준] 1016 제곱 ㄴㄴ 수 (0) | 2021.11.17 |
[백준] 1644 소수의 연속합 (0) | 2021.11.16 |