본문 바로가기

백준 온라인 저지 (BOJ) 문제풀이

백준 온라인 저지 (BOJ) 18422 Emacs

문제

While playing in his favourite text editor, Daniel decided to draw a picture that was N characters high and M characters wide. The picture consists solely of characters ’.’ and ’*’ such that characters ’*’ form some non-overlapping rectangles. The rectangles don’t even touch each other on their sides or corners.

Help Daniel count the number of rectangles drawn on the picture.

입력

The first line contains two integers N and M (1 ≤ N, M ≤ 100) from task description. Each of the next N lines contains M characters ’.’ or ’*’ which represent the picture that Daniel drew.

출력

In a single line you should output the number of rectangles on the picture.

 

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
#include<stdio.h>
#pragma warning(disable:4996)
#pragma warning(disable:6031)
int dx[4= { -1,1,0,0 }, dy[4= { 0,0,-1,1 };
char map[100][102];
int n, m, ans = 0;
void dfs(int y, int x);
int main() {
    scanf("%d%d"&n, &m);
    getchar();
    for (int i = 0; i < n; i++)
        fgets(map[i], m + 2, stdin);
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            if (map[i][j] == '*') {
                ans++;
                dfs(i, j);
            }
        }
    }
    printf("%d\n", ans);
    return 0;
}
void dfs(int y, int x) {
    if (map[y][x] == '*') {
        map[y][x] = '.';
        for (int i = 0; i < 4; i++) {
            int new_y = y + dy[i], new_x = x + dx[i];
            if (new_y < 0 || new_y >= n || new_x < 0 || new_x >= m)continue;
            dfs(new_y, new_x);
        }
    }
}
cs

 

단순한 dfs 문제였다.