@@ -50,3 +50,61 @@ class Solution {
50
50
dfs (board, i, j +1 , m, n);
51
51
}
52
52
};
53
+
54
+ /*
55
+ BFS Solution
56
+ */
57
+
58
+ class Solution {
59
+ private:
60
+ int rows, cols;
61
+
62
+ void bfs (int row,int col, vector<vector<char >>& board) {
63
+ board[row][col] =' E' ;
64
+ queue<pair<int ,int >> q;
65
+ q.push ({row, col});
66
+
67
+ vector<pair<int ,int >> directions = {{0 ,1 }, {1 ,0 }, {-1 ,0 }, {0 , -1 }};
68
+ while (!q.empty ()) {
69
+ auto [r, c] = q.front ();
70
+ q.pop ();
71
+ for (const auto &direction : directions) {
72
+ int newRow = r + direction.first ;
73
+ int newCol = c + direction.second ;
74
+ if (newRow < rows && newRow >=0 && newCol < cols && newCol >=0 && board[newRow][newCol] ==' O' ) {
75
+ board[newRow][newCol] =' E' ;
76
+ q.push ({newRow, newCol});
77
+ }
78
+ }
79
+ }
80
+
81
+ }
82
+
83
+ public:
84
+ void solve (vector<vector<char >>& board) {
85
+ rows = board.size ();
86
+ cols = board[0 ].size ();
87
+
88
+ for (int row =0 ; row < rows; ++row) {
89
+ if (board[row][0 ] ==' O' )bfs (row,0 , board);
90
+ if (board[row][cols -1 ] ==' O' )bfs (row, cols -1 , board);
91
+ }
92
+
93
+ for (int col =0 ; col < cols; ++col) {
94
+ if (board[0 ][col] ==' O' )bfs (0 , col, board);
95
+ if (board[rows -1 ][col] ==' O' )bfs (rows -1 , col, board);
96
+ }
97
+
98
+ for (int row =0 ; row < rows; ++row) {
99
+ for (int col =0 ; col < cols; ++col) {
100
+ if (board[row][col] ==' O' ) {
101
+ board[row][col] =' X' ;
102
+ }
103
+ else if (board[row][col] ==' E' ) {
104
+ board[row][col] =' O' ;
105
+ }
106
+ }
107
+ }
108
+
109
+ }
110
+ };