ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [JAVA] 백준 2667번 단지번호붙이기 BFS , DFS
    코팅테스트 연습/자바 2022. 2. 13. 19:46

    DFS  깊이 우선 탐색으로 

    루트 노드(또는 다른 임의의 노드)에서 시작해서 다음 분기(branch)로 넘어가기 전에 해당 분기를 완벽하게 탐색하는 방법 입니다 . 최대한 깊이 내려가다가 더이상 갈 수 있는 방법이 없으면 다시 가장 가까운 분기점으로 돌아가 다른 분기방향으로 진행하는 것 입니다.


    BFS 는 너비 우선 탐색으로 

    노드 에 연결되어 있는 모든 길을 한번씩 탐색한 뒤 다시 연결되어 있는 모든 길을 넓게 탐색하는 방법입니다

     

     

    출처 :http://blog.hackerearth.com/wp-content/uploads/2015/05/dfsbfs_animation_final.gifhttps://namu.wiki/w/BFS

     

    DFS = 현재 노드에서 최대한 깊이 들어갈 수 있는 점까지 들어가면서 탐색 >> 스택을 사용해 LIFO 을 이용

    BFS = 현재 노드에서 제일 넓게(가까운) 점들부터 탐색 >> 큐를 이용해 FIFO 을 이용

     

     

     

     


    문제

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

    입력

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

    출력

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

    예제 입력 1 복사

    7
    0110100
    0110101
    1110101
    0000111
    0100000
    0111110
    0111000
    

    예제 출력 1 복사

    3
    7
    8
    9
    

     

     

    코드 - BFS 방법

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.LinkedList;
    import java.util.Queue;
    
    public class bj_2667 {
    
    	public static void main(String[] args) throws NumberFormatException, IOException {
    		BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
    		int T =Integer.parseInt(bf.readLine());
    		
    		String map [][] = new String[T][T];
    		
    		for(int i=0; i<T;i++) {
    			map[i] = bf.readLine().split("");
    			
    		}
    		Queue<Integer[]> block = new LinkedList<>();
    		int count =0;
    		ArrayList<Integer> answer = new ArrayList<>();
    		int[][] dir = { { -1, 0 }, { 1, 0 }, { 0, -1 }, { 0, 1 } };
    		for(int i=0; i<T;i++) {
    			for(int j=0; j<T;j++) {
    				if(map[i][j].equals("1")) {
    					count++;
    					map[i][j] ="0";
    					block.add(new Integer[] {i,j});
    					
    					while(!(block.isEmpty())) {
    						Integer[] idx = block.poll();
    						for (int k = 0; k < 4; k++) {
    							int i_i = idx[0] + dir[k][0];
    							int j_j = idx[1]  + dir[k][1];
    							
    							if (i_i < T && i_i >= 0 && j_j < T && j_j >= 0) {
    								
    								if (map[i_i][j_j].equals("1")) {
    									
    									Integer[] temp = {i_i ,j_j};
    									block.add(temp);
    									count++;
    									map[i_i][j_j] ="0";
    								}
    							} 
    						}
    						
    					}
    					answer.add(count);
    					count=0;
    					
    				}
    				
    			}
    			
    		}
    		
    		Collections.sort(answer);
    		System.out.println(answer.size());
    		for(int temp : answer) {
    			System.out.println(temp);
    		}
    		
    		
    		
    
    		
    		
    
    	}
    
    }

     

    코드 DFS 사용

     

     

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.LinkedList;
    import java.util.Queue;
    import java.util.Stack;
    
    public class bj_2667_dfs {
    	public static void main(String[] args) throws NumberFormatException, IOException {
    		BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
    		int T =Integer.parseInt(bf.readLine());
    		
    		String map [][] = new String[T][T];
    		
    		for(int i=0; i<T;i++) {
    			map[i] = bf.readLine().split("");
    			
    		}
    		Stack<Integer[]> block = new Stack<>();
    		int count =0;
    		ArrayList<Integer> answer = new ArrayList<>();
    		int[][] dir = { { -1, 0 }, { 1, 0 }, { 0, -1 }, { 0, 1 } };
    		for(int i=0; i<T;i++) {
    			for(int j=0; j<T;j++) {
    				if(map[i][j].equals("1")) {
    					count++;
    					map[i][j] ="0";
    					block.add(new Integer[] {i,j});
    					
    					while(!(block.isEmpty())) {
    						Integer[] idx = block.pop();
    						for (int k = 0; k < 4; k++) {
    							int i_i = idx[0] + dir[k][0];
    							int j_j = idx[1]  + dir[k][1];
    							
    							if (i_i < T && i_i >= 0 && j_j < T && j_j >= 0) {
    								
    								if (map[i_i][j_j].equals("1")) {
    									
    									Integer[] temp = {i_i ,j_j};
    									block.add(temp);
    									count++;
    									map[i_i][j_j] ="0";
    								}
    							} 
    						}
    						
    					}
    					answer.add(count);
    					count=0;
    					
    				}
    				
    			}
    			
    		}
    		
    		Collections.sort(answer);
    		System.out.println(answer.size());
    		for(int temp : answer) {
    			System.out.println(temp);
    		}
    		
    		
    		
    
    		
    		
    
    	}
    
    }

    댓글

Designed by Tistory.