-
Notifications
You must be signed in to change notification settings - Fork 0
/
replace_'O'_with_'X'.cpp
76 lines (62 loc) · 2.16 KB
/
replace_'O'_with_'X'.cpp
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include<iostream>
#include<vector>
using namespace std;
int main()
{
return 0;
}
// overall time complexity -> O(n * m) [as in worst case when all the elements is O, then only 1 time dfs is called.]
// Time complexity -> O(n * m)
void markedvisited(int row, int col, vector<vector<int>> &vis, vector<vector<char>>& mat){
vis[row][col] = 1;
int n = mat.size();
int m = mat[0].size();
// jo bhi connected O hai, wo sara visit ho jaye.
int delrow[] = {-1, 0, 1, 0};
int delcol[] = {0, 1, 0, -1};
for(int i = 0; i<4; i++){
int nrow = row + delrow[i];
int ncol = col + delcol[i];
if(nrow >= 0 && nrow < n && ncol >= 0 && ncol < m && !vis[nrow][ncol] && mat[nrow][ncol] == 'O'){
markedvisited(nrow, ncol, vis, mat);
}
}
}
vector<vector<char>> fill(int n, int m, vector<vector<char>> mat)
{
// this can be done using the bfs and dfs both.
vector<vector<char>> ans = mat;
vector<vector<int>> vis(n , vector<int>(m, 0));
// first traverse the boundary 'O' and marked them visited.
// Time complexity -> O(N)
for(int i = 0; i<n; i++){
// first col
if(mat[i][0] == 'O' && !vis[i][0]){
markedvisited(i, 0, vis, mat);
}
// last col
if(mat[i][m-1] == 'O' && !vis[i][m-1]){
markedvisited(i, m-1, vis, mat);
}
}
// Time complexity -> O(M)
for(int i = 0; i<m; i++){
// first row
if(mat[0][i] == 'O' && !vis[0][i] ){
markedvisited(0, i, vis, mat);
}
// last row
if(mat[n-1][i] == 'O' && !vis[n-1][i]){
markedvisited(n-1, i, vis, mat);
}
}
// Time complexity -> O(N * M)
for(int i = 0; i<n; i++){
for(int j = 0; j<m; j++){
if(ans[i][j] == 'O' && !vis[i][j]){
ans[i][j] = 'X';
}
}
}
return ans;
}