티스토리 뷰

[BJ] 2667. 단지번호붙이기 

www.acmicpc.net/problem/2667

 

2667번: 단지번호붙이기

<그림 1>과 같이 정사각형 모양의 지도가 있다. 1은 집이 있는 곳을, 0은 집이 없는 곳을 나타낸다. 철수는 이 지도를 가지고 연결된 집의 모임인 단지를 정의하고, 단지에 번호를 붙이려 한다. 여

www.acmicpc.net

import java.io.*;
import java.util.*;
// 210212

public class Main_BJ_2667_단지번호붙이기 {
	
	static int N;
	static int[][] map;
	static boolean[][] visited;
	static int[] dr = {-1, 0, 1, 0};
	static int[] dc = {0, -1, 0, 1};
	static int total = 0, cnt = 0;
	
	static void dfs(int r, int c) {
		visited[r][c] = true;
		
		for(int d=0; d<4; d++) {
			int nr = r + dr[d];
			int nc = c + dc[d];
			if (nr>=0 && nr<N && nc>=0 && nc<N 
					&& map[nr][nc]==1 && !visited[nr][nc]) {
				++cnt;
				visited[nr][nc] = true;
				dfs(nr, nc);
			} 
		}
	}

	public static void main(String[] args) throws Exception {
		System.setIn(new FileInputStream("res/input_BJ_2667_단지번호붙이기.txt"));
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		
		N = Integer.parseInt(br.readLine());
		map = new int[N][N];
		visited = new boolean[N][N];
		ArrayList<Integer> list = new ArrayList<Integer>();

		for(int r=0; r<N; r++) {
			String[] arr = br.readLine().split("");
			for(int c=0; c<N; c++) {
				map[r][c] = Integer.parseInt(arr[c]);
			}
		}
		
		for(int r=0; r<N; r++) {
			for(int c=0; c<N; c++) {
				if (map[r][c] == 0) {
					visited[r][c] = true;
				}
				else {
					if (!visited[r][c]) {		
						cnt = 1;
						dfs(r, c);
						list.add(cnt);
						total++;
					}
				}
			}
		}
		
		Collections.sort(list);
		
		StringBuilder sb = new StringBuilder();
		sb.append(total + "\n");
		for(int i=0; i<total; i++) {
			sb.append(list.get(i) + "\n");
		}
		System.out.println(sb.toString());
		
		br.close();
	} // main
}

'코딩테스트 > 백준' 카테고리의 다른 글

[BJ] 7562. 나이트의 이동  (0) 2021.02.15
[BJ] 1707. 이분 그래프  (0) 2021.02.15
[BJ] 7569. 토마토  (0) 2021.02.14
[BJ] 2606. 바이러스  (0) 2021.02.14
[BJ] 1260. DFS와 BFS  (0) 2021.02.14
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
글 보관함