[Geeks for Geeks] Replace Os with Xs

Replace O’s with X’s

Given a matrix mat of size N x M where every element is either ‘O’ or ‘X’.
Replace all ‘O’ with ‘X’ that are surrounded by ‘X’.
A ‘O’ (or a set of ‘O’) is considered to be by surrounded by ‘X’ if there are ‘X’ at locations just below, just above, just left and just right of it.

  • Time : O(nm)
  • Space : O(n + m)
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
class Solution {
void bfs(vector<vector<char>>& mat, int sy, int sx, int n, int m) {
int dy[4]{-1,0,1,0}, dx[4]{0,1,0,-1};
queue<pair<int,int>> q;
q.push({sy,sx});
mat[sy][sx] = '#';
while(!q.empty()) {
auto p = q.front(); q.pop();
auto y = p.first, x = p.second;
for(int i = 0; i < 4; i++) {
int ny = y + dy[i], nx = x + dx[i];
if(0 <= ny and ny < n and 0 <= nx and nx < m and mat[ny][nx] == 'O') {
mat[ny][nx] = '#';
q.push({ny,nx});
}
}
}
}
public:
vector<vector<char>> fill(int n, int m, vector<vector<char>> mat) {
for(int i = 0; i < n; i++) {
if(mat[i][0] == 'O') bfs(mat,i,0,n,m);
if(mat[i][m-1] == 'O') bfs(mat,i,m-1,n,m);
}
for(int j = 0; j < m; j++) {
if(mat[0][j] == 'O') bfs(mat,0,j,n,m);
if(mat[n-1][j] == 'O') bfs(mat,n-1,j,n,m);
}
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
if(mat[i][j] == 'O') mat[i][j] = 'X';
else if(mat[i][j] == '#') mat[i][j] = 'O';
}
}
return mat;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/15/PS/GeeksforGeeks/replace-os-with-xs/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.