알고리즘/백준
[C++/BFS] 백준 3184 양
waterground
2019. 7. 8. 16:42
코드
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 | #include <iostream> #include <queue> using namespace std; int r, c; int sheepRes = 0, wolfRes = 0; // 최종 양, 늑대 수 char map[251][251]; // 지도 bool visit[251][251]; // bfs 수행시 방문 여부를 표시할 배열 queue<pair<int, int>> q; // bfs에 이용할 큐. <행, 열> int nowX, nowY, newX, newY; void bfs(int i, int j) { int move[4][2] = { { 1, 0 },{ -1, 0 },{ 0, 1 },{ 0, -1 } }; // 이동 할 수 있는 경우의 수 int sheepCnt = 0, wolfCnt = 0; q.push({ i, j }); // 시작점을 넣어 큐가 비지 않도록 visit[i][j] = true; // 방문 표시 while (!q.empty()) { nowX = q.front().first; // 현재 행 위치 nowY = q.front().second; // 현재 열 위치 q.pop(); // 현재 위치에 늑대/양이 있을 경우 if (map[nowX][nowY] == 'v') wolfCnt++; else if (map[nowX][nowY] == 'o') sheepCnt++; // move 배열을 이용해 동서남북으로 이동 for (int i = 0; i < 4; i++) { newX = nowX + move[i][0]; // 이동 후의 행 위치 newY = nowY + move[i][1]; // 이동 후의 열 위치 // 범위를 벗어나는 것을 막기 위해 if (newX < r && newX >= 0 && newY < c && newY >= 0) // 울타리가 아니어서 이동 할 수 있고, bfs로 이동하지 않은 경우 if (map[newX][newY] != '#' && !visit[newX][newY]) { q.push({ newX, newY }); visit[newX][newY] = true; // 방문 표시 } } } } // 늑대가 이길 경우 if (sheepCnt <= wolfCnt) wolfRes += wolfCnt; // 양이 이길 경우 else sheepRes += sheepCnt; } int main() { cin >> r >> c; // 행, 열 크기 입력 for (int i = 0; i < r; i++) cin >> map[i]; fill(&visit[0][0], &visit[250][251], false); // 방문 표시 배열 초기화 for (int i = 0; i < r; i++) for (int j = 0; j < c; j++) // 방문하지 않았거나(이전에 bfs를 수행하지 않았거나) // 울타리(#)가 아닌 경우 bfs 수행 if (map[i][j] != '#' && visit[i][j] == false) bfs(i, j); printf("%d %d", sheepRes, wolfRes); } | cs |