BOJ::2667 단지 번호 붙이기
https://www.acmicpc.net/problem/2667
탐색 및 카운팅만 해주면 되는 문제.
라이브러리 안쓰고 풀고 싶은데 어렵기도 하고 습관이 쉽게 바뀌지 않는다..
<JAVA>
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 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; public class Main { static int n,cnt,ax,ay; static int map[][]=new int[25][25]; static int dx[]={1,-1,0,0}; static int dy[]={0,0,1,-1}; public static void main(String args[]) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); ArrayList<Integer> res = new ArrayList(); n = Integer.parseInt(br.readLine()); for(int i = 0 ; i < n ; i++){ String s=br.readLine(); for(int j = 0 ; j < n ; j++){ map[i][j]=s.charAt(j); } } for(int i = 0 ; i < n ; i ++){ for(int j = 0 ; j < n ; j++){ if(map[i][j]=='1'){ cnt=0; int v = dfs(i,j); res.add(v); } } } Collections.sort(res); System.out.println(res.size()); for(int vv : res){ System.out.println(vv+" "); } } public static int dfs(int x,int y){ map[x][y]='0'; cnt++; for(int i =0 ; i < 4 ; i++){ ax=x+dx[i]; ay=y+dy[i]; if(ax>=0&&ay>=0&&ax<n&&ay<n){ if(map[ax][ay]=='1')dfs(ax,ay); } } return cnt; } } | cs |
<C++>
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 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | #include <iostream> #include <string> #include <algorithm> using namespace std; int res[25 * 25]; int n,cnt,ax,ay; int map[25][25]; int dx[] = { 1,-1,0,0 }; int dy[] = { 0,0,1,-1 }; int dfs(int x, int y) { cnt++; map[x][y] = '0'; for (int i = 0; i < 4; i++) { ax = x + dx[i]; ay = y + dy[i]; if (ax >= 0 && ay >= 0 && ax < n&&ay < n) { if (map[ax][ay] == '1') { dfs(ax, ay); } } } return cnt; } int main() { cin >> n; for (int i = 0; i < n; i++) { string s; cin >> s; for (int j = 0; j < n; j++) { map[i][j] = s.at(j); } } int idx = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (map[i][j] == '1') { cnt = 0; int vv = dfs(i, j); res[idx] = vv; idx++; } } } sort(res, res + idx); cout << idx<< endl; for (int i = 0; i < idx; i++) { cout << res[i] << "\n"; } } | cs |
'BOJ::문제풀이' 카테고리의 다른 글
3187 양치기 꿍 (0) | 2018.01.06 |
---|---|
2668 숫자고르기 (0) | 2018.01.06 |
2589 보물섬 (0) | 2018.01.04 |
2579 계단 오르기 (0) | 2018.01.04 |
2573 빙산 (0) | 2018.01.01 |