-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSurrounded_regions_or_replace_O's_with_X's.cpp
More file actions
99 lines (87 loc) · 2.5 KB
/
Surrounded_regions_or_replace_O's_with_X's.cpp
File metadata and controls
99 lines (87 loc) · 2.5 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
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
//{ Driver Code Starts
// Initial Template for C++
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
// User function Template for C++
class Solution{
private:
void dfs(int row, int col, vector<vector<int>>&vis,
vector<vector<char>>&mat, int delrow[], int delcol[])
{
vis[row][col] = 1;
int n = mat.size();
int m = mat[0].size();
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')
{
dfs(nrow, ncol, vis, mat, delrow, delcol);
}
}
}
public:
vector<vector<char>> fill(int n, int m, vector<vector<char>> mat)
{
vector<vector<int>> vis(n, vector<int>(m, 0));
int delrow[] = {-1, 0, +1, 0};
int delcol[] = {0, +1, 0, -1};
for(int j = 0; j < m ; j++)
{
if(!vis[0][j] && mat[0][j] == 'O')
{
dfs(0, j, vis, mat, delrow, delcol);
}
if(!vis[n-1][j] && mat[n-1][j] == 'O')
{
dfs(n-1, j, vis, mat, delrow, delcol);
}
}
for(int i = 0; i < n ; i++)
{
if(!vis[i][0] && mat[i][0] == 'O')
{
dfs(i, 0, vis, mat, delrow, delcol);
}
if(!vis[i][m-1] && mat[i][m-1] == 'O')
{
dfs(i, m-1, vis, mat, delrow, delcol);
}
}
for(int i = 0; i < n; i++)
{
for(int j = 0; j < m; j++)
{
if(!vis[i][j] && mat[i][j] == 'O')
mat[i][j] = 'X';
}
}
return mat;
}
};
//{ Driver Code Starts.
int main(){
int t;
cin>>t;
while(t--){
int n, m;
cin>>n>>m;
vector<vector<char>> mat(n, vector<char>(m, '.'));
for(int i = 0;i < n;i++)
for(int j=0; j<m; j++)
cin>>mat[i][j];
Solution ob;
vector<vector<char>> ans = ob.fill(n, m, mat);
for(int i = 0;i < n;i++) {
for(int j = 0;j < m;j++) {
cout<<ans[i][j]<<" ";
}
cout<<"\n";
}
}
return 0;
}
// } Driver Code Ends