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


#include <vector>

using namespace std;

void travel(vector<vector<char> > &board, int i, int j) {
    if (i < 0 || j < 0 
        || board.size() <= i || board[0].size() <= j)
        return;
    
    if (board[i][j] != 'O') return;
    
    board[i][j] = 'V'; // mark the position has been visited
    travel(board, i-1, j);
    travel(board, i+1, j);
    travel(board, i, j-1);
    travel(board, i, j+1);
}

void solve(vector<vector<char> > &board) {
    size_t rows = board.size();
    if (rows <= 0) return;
    
    size_t cols = board[0].size();
    for (int j = 0; j < cols; ++j) {
        if (board[0][j] == 'O')
            travel(board, 0, j);
        
        if (board[rows-1][j] == 'O')
            travel(board, rows-1, j);
    }
    
    for (int i = 0; i < rows; ++i) {
        if (board[i][0] == 'O') 
            travel(board, i, 0);
        
        if (board[i][cols-1] == 'O') 
            travel(board, i, cols-1);
    }
    
    for (int i = 0; i < rows; ++i) {
        for (int j = 0; j < cols; ++j) {
            if (board[i][j] == 'O')
                board[i][j] = 'X';
            
            if (board[i][j] == 'V')
                board[i][j] = 'O';
        }
    }
}
View Program Text


Test Status