BOJ
백준 1012 / 유기농 배추
로봇이아닙니다
2018. 12. 31. 16:12
BFS를 이용한 가장 기본적인 문제기 때문에 나중에 한번 더 풀어봐야 겠다.
BFS문제
배추가 있는 곳을 큐에 넣지말고
맵을 서치하면서 하나씩 큐에 넣고 인접한 것들에 서치값을 -1로 만들면서
확인하면 된다.
코드
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 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 | #include <stdio.h> #include <iostream> #include <vector> #include <queue> using namespace std; int n, m, w; int map[51][51]; int d[51][51]; int dx[] = { 1,-1,0,0 }; int dy[] = { 0,0,1,-1 }; queue <pair<int,int>> q; int cnt = 0; void bfs(int i,int j) { q.push(make_pair(i, j)); while (!q.empty()) { int x = q.front().first; int y = q.front().second; q.pop(); for (int i = 0; i < 4; i++) { int nx = x + dx[i]; int ny = y + dy[i]; if (nx >= 0 && ny >= 0 && nx < n && ny < m) { if (map[nx][ny] == 1 && d[nx][ny] == 0) { d[nx][ny] = -1; q.push(make_pair(nx, ny)); } } } } } int main() { //freopen("Text.txt", "r", stdin); int testcase; cin >> testcase; while (testcase--) { cnt = 0; cin >> m >> n >> w; for (int i = 0; i < w; i++) { int x, y; cin >> x >> y; map[y][x] = 1; } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (map[i][j] == 1 &&d[i][j]==0) { bfs(i, j); cnt++; } } } cout << cnt << endl; for (int i = 0; i < 51; i++) { for (int j = 0; j < 51; j++) { map[i][j] = 0; d[i][j] = 0; } } } } | cs |