알고리즘 문제

[백준] boj 2667 java "단지 번호 붙이기" - dfs, bfs

민돌v 2022. 3. 25. 01:33
728x90

문제 링크

성능 요약

메모리: 14668 KB, 시간: 148 ms

분류

너비 우선 탐색(bfs), 깊이 우선 탐색(dfs), 그래프 이론(graphs), 그래프 탐색(graph_traversal)

문제 설명

<그림 1>과 같이 정사각형 모양의 지도가 있다. 1은 집이 있는 곳을, 0은 집이 없는 곳을 나타낸다. 철수는 이 지도를 가지고 연결된 집의 모임인 단지를 정의하고, 단지에 번호를 붙이려 한다. 여기서 연결되었다는 것은 어떤 집이 좌우, 혹은 아래위로 다른 집이 있는 경우를 말한다. 대각선상에 집이 있는 경우는 연결된 것이 아니다. <그림 2>는 <그림 1>을 단지별로 번호를 붙인 것이다. 지도를 입력하여 단지수를 출력하고, 각 단지에 속하는 집의 수를 오름차순으로 정렬하여 출력하는 프로그램을 작성하시오.

입력

첫 번째 줄에는 지도의 크기 N(정사각형이므로 가로와 세로의 크기는 같으며 5≤N≤25)이 입력되고, 그 다음 N줄에는 각각 N개의 자료(0혹은 1)가 입력된다.

출력

첫 번째 줄에는 총 단지수를 출력하시오. 그리고 각 단지내 집의 수를 오름차순으로 정렬하여 한 줄에 하나씩 출력하시오.

 


[문제 해결]

dfs 와 bfs를 이용해서 풀 수 있다.

방문처리를 신경쓰면서 풀자

 

[bfs]

package solved.Class;
import java.io.*;
import java.util.*;

class dot{
    int x;
    int y;
    dot(int x, int y){
        this.x=x;
        this.y=y;
    }
}
public class Main {
    static int map[][];
    static int dx[] ={1,0,-1,0};
    static int dy[] = {0,1,0,-1};

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));

        String temp[] ;
        int n = Integer.parseInt(br.readLine());

        map = new int[n][n];

        for(int i=0;i<n;i++){
            temp = br.readLine().split("");
            for(int j=0;j<n;j++)
                map[i][j] = Integer.parseInt(temp[j]);
        }
        int result = 0;
        ArrayList<Integer> list = new ArrayList<Integer>();

        for(int i=0;i<n;i++){
            for(int j=0;j<n;j++){
                if(map[i][j]!=0){
                    result++;
                    list.add(bfs(i,j,n));
                }
            }
        }

        System.out.println(result);
        Collections.sort(list);
        for(int a : list)
            System.out.println(a);
    }

    public static int bfs(int x, int y, int n){
        int cnt=0;

        ArrayDeque<dot> dq = new ArrayDeque<>();
        dq.add(new dot(x,y));
        map[x][y] = 0;

        while(!dq.isEmpty()) {
            cnt++;
            dot now = dq.poll();

            for (int i = 0; i < 4; i++) {
                int nx = now.x + dx[i];
                int ny = now.y + dy[i];

                if (nx < 0 || ny < 0 || nx >= n || ny >= n || map[nx][ny]==0)
                    continue;

                dq.add(new dot(nx,ny));
                map[nx][ny] = 0;

            }
        }
        return cnt;
    }
}

 

[dfs]


public class Main {

	static int dx[] = {1,0,-1,0};
	static int dy[] = {0,1,0,-1};
	
	static int count =0;
	
	static ArrayList<Integer> result = new ArrayList<Integer>();
	static boolean[][] visit;
	
	public static void main(String[] args) throws IOException{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		
		int n = Integer.parseInt(br.readLine());
		int map[][] = new int[n][n];
		
		for(int i=0;i<n;i++) {
			String temp[] = br.readLine().split("");
			for(int j=0;j<n;j++) {
				map[i][j] = Integer.parseInt(temp[j]);
			}
		}
		
		visit = new boolean[n][n];
		
		for(int i=0;i<n;i++) {
			for(int j=0;j<n;j++) {
				if(map[i][j]==1 && !visit[i][j]) {
					dfs(i,j,map,n);
					
					result.add(count);
					count=0;
				}
			}
		}
		System.out.println(result.size());
		Collections.sort(result);
		for(int a : result)
			System.out.println(a);
	}
	
	public static void dfs(int x,int y, int map[][], int size) {
		if(visit[x][y] || map[x][y] ==0) 
			return;
		
		visit[x][y] = true;
		if(map[x][y] == 1)
			count++;
		
		for(int i =0;i<4;i++) {
			int nextx = x+dx[i];
			int nexty = y+dy[i];
			
			//map을 벗어나는 경우
			if(nextx<0 || nexty<0 || nextx >=size || nexty >=size)
				continue;
			
			
			dfs(nextx,nexty,map,size);
		}
		
		
		
	}
}
반응형