알고리즘

[백준] 2667번 (java 자바)

changha. 2022. 10. 6. 23:02
import java.util.*;

public class Main
{   
    static final int MAX_N = 30;
    static int N;
    static boolean[][] visited = new boolean[MAX_N][MAX_N];
    static int[][] matrix = new int[MAX_N][MAX_N];
    static int[][] D = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
    static int cnt = 0;
    static List<Integer> list = new ArrayList<Integer>();
    static class Point{
        Point(int r, int c, int d){
            row = r; col = c; dist = d;
        }
        int row, col, dist;
    }
	public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        N = sc.nextInt();

        for(int i=0; i<N; i++){
            String input = sc.next();
            for(int j=0; j<N; j++){
                matrix[i][j] = input.charAt(j)-'0';
            }
        }
        
        for(int i = 0; i < N; i++){
            for(int j = 0; j < N; j++){
                if(matrix[i][j] == 1){
                    bfs(i, j);
                    cnt++;
                }
            }
        }
        Collections.sort(list);
        System.out.println(cnt);
        for(int i = 0; i < cnt; i++){
            System.out.println(list.get(i));
        }
        
	}
	static void bfs(int u, int v){
        Queue<Point> myqueue = new LinkedList<>();
        myqueue.add(new Point(u, v, 1));
        visited[u][v] = true;
        int a = 0;
        
        while(!myqueue.isEmpty()){
            Point curr = myqueue.remove();
            a++;
            
            for(int i = 0; i < 4; i++){
                int nr = curr.row + D[i][0];
                int nc = curr.col + D[i][1];
                if(nr < 0 || nr > N - 1 || nc < 0 || nc > N - 1) continue;
                if(visited[nr][nc]) continue;
                if(matrix[nr][nc] == 0) continue;
                myqueue.add(new Point(nr, nc, curr.dist +1));
                matrix[nr][nc] = 0;

            }
        }
        list.add(a);
        
	    }
	}

다른 코드들이랑 비교 해보기 

'알고리즘' 카테고리의 다른 글

다익스트라(Dijkstra) 기본 알고리즘  (0) 2022.10.12
[백준] 1012번(java 자바)  (0) 2022.10.10
<백준> 2606번 자바 알고리즘[BFS]  (0) 2022.10.06
[백준] 2178번 (java 자바)  (0) 2022.10.05
DFS 기본 알고리즘  (0) 2022.09.28