forked from dimpeshmalviya/C-Language-Programs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbfsSolve.cpp
More file actions
49 lines (42 loc) · 1.3 KB
/
bfsSolve.cpp
File metadata and controls
49 lines (42 loc) · 1.3 KB
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
void solve(vector<vector<char>>& board) {
int m = board.size();
if (m == 0) return;
int n = board[0].size();
vector<vector<int>> visited(m, vector<int>(n, 0));
queue<pair<int, int>> q;
// Step 1: Push all border 'O's into the queue and mark visited
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (board[i][j] == 'O' && (i == 0 || j == 0 || i == m - 1 || j == n - 1)) {
q.push({i, j});
visited[i][j] = 1;
}
}
}
// Step 2: BFS from border 'O's
int dr[] = {1, 0, -1, 0};
int dc[] = {0, 1, 0, -1};
while (!q.empty()) {
int row = q.front().first;
int col = q.front().second;
q.pop();
for (int i = 0; i < 4; i++) {
int r = row + dr[i];
int c = col + dc[i];
if (r >= 0 && r < m && c >= 0 && c < n) {
if (board[r][c] == 'O' && visited[r][c] == 0) {
visited[r][c] = 1;
q.push({r, c});
}
}
}
}
// Step 3: Flip unvisited 'O's to 'X'
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (board[i][j] == 'O' && visited[i][j] == 0) {
board[i][j] = 'X';
}
}
}
}