|
| 1 | +/* |
| 2 | +* Author: illuz <iilluzen[at]gmail.com> |
| 3 | +* File: AC_bfs_n.cpp |
| 4 | +* Create Date: 2015-03-14 21:36:32 |
| 5 | +* Descripton: BFS, update O in origin map. |
| 6 | +*/ |
| 7 | + |
| 8 | +#include <bits/stdc++.h> |
| 9 | + |
| 10 | +using namespace std; |
| 11 | +const int N = 0; |
| 12 | + |
| 13 | +class Solution { |
| 14 | +private: |
| 15 | + const int dx[4] = {0, 0, 1, -1}; |
| 16 | + const int dy[4] = {1, -1, 0, 0}; |
| 17 | + void bfs(int x, int y, vector<vector<char> > &board) { |
| 18 | + int n = board.size(), m = board[0].size(); |
| 19 | + queue<pair<int, int> > q; |
| 20 | + q.push(make_pair(x, y)); |
| 21 | + board[x][y] = '+'; |
| 22 | + |
| 23 | + while (!q.empty()) { |
| 24 | + x = q.front().first; |
| 25 | + y = q.front().second; |
| 26 | + q.pop(); |
| 27 | + // go to 4 directions |
| 28 | + for (int i = 0; i < 4; ++i) { |
| 29 | + int nx = x + dx[i], ny = y + dy[i]; |
| 30 | + if (nx >= 0 && nx < n && ny >= 0 && ny < m && board[nx][ny] == 'O') { |
| 31 | + board[nx][ny] = '+'; |
| 32 | + q.push(make_pair(nx, ny)); |
| 33 | + } |
| 34 | + } |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | +public: |
| 39 | + void solve(vector<vector<char>> &board) { |
| 40 | + if (board.empty() || board[0].empty()) |
| 41 | + return; |
| 42 | + |
| 43 | + int n = board.size(), m = board[0].size(); |
| 44 | + if (n <= 2 || m <= 2) |
| 45 | + return; |
| 46 | + |
| 47 | + // find side O |
| 48 | + for (int i = 0; i < n; ++i) { |
| 49 | + if (board[i][0] == 'O') |
| 50 | + bfs(i, 0, board); |
| 51 | + if (board[i][m - 1] == 'O') |
| 52 | + bfs(i, m - 1, board); |
| 53 | + } |
| 54 | + for (int j = 0; j < m; ++j) { |
| 55 | + if (board[0][j] == 'O') |
| 56 | + bfs(0, j, board); |
| 57 | + if (board[n - 1][j] == 'O') |
| 58 | + bfs(n - 1, j, board); |
| 59 | + } |
| 60 | + |
| 61 | + // change board |
| 62 | + for (int i = 0; i < n; ++i) |
| 63 | + for (int j = 0; j < m; ++j) |
| 64 | + if (board[i][j] == '+') |
| 65 | + board[i][j] = 'O'; |
| 66 | + else if (board[i][j] == 'O') |
| 67 | + board[i][j] = 'X'; |
| 68 | + |
| 69 | + } |
| 70 | +}; |
| 71 | + |
| 72 | +int main() { |
| 73 | + int n; |
| 74 | + cin >> n; |
| 75 | + vector<vector<char> > inp(n); |
| 76 | + for (auto &i : inp) { |
| 77 | + string str; |
| 78 | + cin >> str; |
| 79 | + for (auto & j : str) |
| 80 | + i.push_back(j); |
| 81 | + } |
| 82 | + Solution s; |
| 83 | + s.solve(inp); |
| 84 | + return 0; |
| 85 | +} |
| 86 | + |
0 commit comments