Open In App

# Given a matrix of ‘O’ and ‘X’, replace ‘O’ with ‘X’ if surrounded by ‘X’

Given a matrix where every element is either ‘O’ or ‘X’, replace ‘O’ with ‘X’ if 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.

Examples:

`Input: mat[M][N] =  {{'X', 'O', 'X', 'X', 'X', 'X'},                     {'X', 'O', 'X', 'X', 'O', 'X'},                     {'X', 'X', 'X', 'O', 'O', 'X'},                     {'O', 'X', 'X', 'X', 'X', 'X'},                     {'X', 'X', 'X', 'O', 'X', 'O'},                     {'O', 'O', 'X', 'O', 'O', 'O'},                    };Output: mat[M][N] =  {{'X', 'O', 'X', 'X', 'X', 'X'},                      {'X', 'O', 'X', 'X', 'X', 'X'},                      {'X', 'X', 'X', 'X', 'X', 'X'},                      {'O', 'X', 'X', 'X', 'X', 'X'},                      {'X', 'X', 'X', 'O', 'X', 'O'},                      {'O', 'O', 'X', 'O', 'O', 'O'},                    };`
`Input: mat[M][N] =  {{'X', 'X', 'X', 'X'}                     {'X', 'O', 'X', 'X'}                     {'X', 'O', 'O', 'X'}                     {'X', 'O', 'X', 'X'}                     {'X', 'X', 'O', 'O'}                    };                    Output: mat[M][N] =  {{'X', 'X', 'X', 'X'}                     {'X', 'X', 'X', 'X'}                     {'X', 'X', 'X', 'X'}                     {'X', 'X', 'X', 'X'}                     {'X', 'X', 'O', 'O'}                    };                     `

This is mainly an application of Flood-Fill algorithm. The main difference here is that a ‘O’ is not replaced by ‘X’ if it lies in region that ends on a boundary. Following are simple steps to do this special flood fill.

1. Traverse the given matrix and replace all ‘O’ with a special character ‘-‘.
2. Traverse four edges of given matrix and call floodFill(‘-‘, ‘O’) for every ‘-‘ on edges. The remaining ‘-‘ are the characters that indicate ‘O’s (in the original matrix) to be replaced by ‘X’.
3. Traverse the matrix and replace all ‘-‘s with ‘X’s.

Let us see steps of above algorithm with an example. Let following be the input matrix.

`       mat[M][N] =  {{'X', 'O', 'X', 'X', 'X', 'X'},                     {'X', 'O', 'X', 'X', 'O', 'X'},                     {'X', 'X', 'X', 'O', 'O', 'X'},                     {'O', 'X', 'X', 'X', 'X', 'X'},                     {'X', 'X', 'X', 'O', 'X', 'O'},                     {'O', 'O', 'X', 'O', 'O', 'O'},                    };`

Step 1: Replace all ‘O’ with ‘-‘.

`       mat[M][N] =  {{'X', '-', 'X', 'X', 'X', 'X'},                     {'X', '-', 'X', 'X', '-', 'X'},                     {'X', 'X', 'X', '-', '-', 'X'},                     {'-', 'X', 'X', 'X', 'X', 'X'},                     {'X', 'X', 'X', '-', 'X', '-'},                     {'-', '-', 'X', '-', '-', '-'},                    };`

Step 2: Call floodFill(‘-‘, ‘O’) for all edge elements with value equals to ‘-‘

`       mat[M][N] =  {{'X', 'O', 'X', 'X', 'X', 'X'},                     {'X', 'O', 'X', 'X', '-', 'X'},                     {'X', 'X', 'X', '-', '-', 'X'},                     {'O', 'X', 'X', 'X', 'X', 'X'},                     {'X', 'X', 'X', 'O', 'X', 'O'},                     {'O', 'O', 'X', 'O', 'O', 'O'},                    };`

Step 3: Replace all ‘-‘ with ‘X’.

`       mat[M][N] =  {{'X', 'O', 'X', 'X', 'X', 'X'},                     {'X', 'O', 'X', 'X', 'X', 'X'},                     {'X', 'X', 'X', 'X', 'X', 'X'},                     {'O', 'X', 'X', 'X', 'X', 'X'},                     {'X', 'X', 'X', 'O', 'X', 'O'},                     {'O', 'O', 'X', 'O', 'O', 'O'},                    };`

The following is implementation of above algorithm.

## C++

 `// A C++ program to replace all 'O's with 'X''s if surrounded by 'X'``#include``using` `namespace` `std;` `// Size of given matrix is M X N``#define M 6``#define N 6`  `// A recursive function to replace previous value 'prevV' at  '(x, y)'``// and all surrounding values of (x, y) with new value 'newV'.``void` `floodFillUtil(``char` `mat[][N], ``int` `x, ``int` `y, ``char` `prevV, ``char` `newV)``{``    ``// Base cases``    ``if` `(x < 0 || x >= M || y < 0 || y >= N)``        ``return``;``    ``if` `(mat[x][y] != prevV)``        ``return``;` `    ``// Replace the color at (x, y)``    ``mat[x][y] = newV;` `    ``// Recur for north, east, south and west``    ``floodFillUtil(mat, x+1, y, prevV, newV);``    ``floodFillUtil(mat, x-1, y, prevV, newV);``    ``floodFillUtil(mat, x, y+1, prevV, newV);``    ``floodFillUtil(mat, x, y-1, prevV, newV);``}` `// Returns size of maximum size subsquare matrix``// surrounded by 'X'``int` `replaceSurrounded(``char` `mat[][N])``{``   ``// Step 1: Replace all 'O'  with '-'``   ``for` `(``int` `i=0; i

## Java

 `// A Java program to replace``// all 'O's with 'X''s if``// surrounded by 'X'``import` `java.io.*;` `class` `GFG``{``    ``static` `int` `M = ``6``;``    ``static` `int` `N = ``6``;``    ``static` `void` `floodFillUtil(``char` `mat[][], ``int` `x,``                              ``int` `y, ``char` `prevV,``                              ``char` `newV)``    ``{``        ``// Base cases``        ``if` `(x < ``0` `|| x >= M ||``            ``y < ``0` `|| y >= N)``            ``return``;``            ` `        ``if` `(mat[x][y] != prevV)``            ``return``;``    ` `        ``// Replace the color at (x, y)``        ``mat[x][y] = newV;``    ` `        ``// Recur for north,``        ``// east, south and west``        ``floodFillUtil(mat, x + ``1``, y,``                      ``prevV, newV);``        ``floodFillUtil(mat, x - ``1``, y,``                      ``prevV, newV);``        ``floodFillUtil(mat, x, y + ``1``,``                      ``prevV, newV);``        ``floodFillUtil(mat, x, y - ``1``,``                      ``prevV, newV);``    ``}``    ` `    ``// Returns size of maximum``    ``// size subsquare matrix``    ``// surrounded by 'X'``    ``static` `void` `replaceSurrounded(``char` `mat[][])``    ``{``        ` `    ``// Step 1: Replace``    ``// all 'O' with '-'``    ``for` `(``int` `i = ``0``; i < M; i++)``        ``for` `(``int` `j = ``0``; j < N; j++)``            ``if` `(mat[i][j] == ``'O'``)``                ``mat[i][j] = ``'-'``;``    ` `    ``// Call floodFill for``    ``// all '-' lying on edges``    ``for` `(``int` `i = ``0``; i < M; i++) ``// Left side``        ``if` `(mat[i][``0``] == ``'-'``)``            ``floodFillUtil(mat, i, ``0``,``                          ``'-'``, ``'O'``);``    ``for` `(``int` `i = ``0``; i < M; i++) ``// Right side``        ``if` `(mat[i][N - ``1``] == ``'-'``)``            ``floodFillUtil(mat, i, N - ``1``,``                          ``'-'``, ``'O'``);``    ``for` `(``int` `i = ``0``; i < N; i++) ``// Top side``        ``if` `(mat[``0``][i] == ``'-'``)``            ``floodFillUtil(mat, ``0``, i,``                          ``'-'``, ``'O'``);``    ``for` `(``int` `i = ``0``; i < N; i++) ``// Bottom side``        ``if` `(mat[M - ``1``][i] == ``'-'``)``            ``floodFillUtil(mat, M - ``1``,``                          ``i, ``'-'``, ``'O'``);``    ` `    ``// Step 3: Replace``    ``// all '-' with 'X'``    ``for` `(``int` `i = ``0``; i < M; i++)``        ``for` `(``int` `j = ``0``; j < N; j++)``            ``if` `(mat[i][j] == ``'-'``)``                ``mat[i][j] = ``'X'``;``    ``}``    ` `    ``// Driver Code``    ``public` `static` `void` `main (String[] args)``    ``{``        ``char``[][] mat = {{``'X'``, ``'O'``, ``'X'``,``                         ``'O'``, ``'X'``, ``'X'``},``                        ``{``'X'``, ``'O'``, ``'X'``,``                         ``'X'``, ``'O'``, ``'X'``},``                        ``{``'X'``, ``'X'``, ``'X'``,``                         ``'O'``, ``'X'``, ``'X'``},``                        ``{``'O'``, ``'X'``, ``'X'``,``                         ``'X'``, ``'X'``, ``'X'``},``                        ``{``'X'``, ``'X'``, ``'X'``,``                         ``'O'``, ``'X'``, ``'O'``},``                        ``{``'O'``, ``'O'``, ``'X'``,``                         ``'O'``, ``'O'``, ``'O'``}};``                        ` `        ``replaceSurrounded(mat);``    ` `        ``for` `(``int` `i = ``0``; i < M; i++)``        ``{``            ``for` `(``int` `j = ``0``; j < N; j++)``                ``System.out.print(mat[i][j] + ``" "``);``                ` `            ``System.out.println(``""``);``        ``}``    ``}``}` `// This code is contributed``// by shiv_bhakt`

## Python3

 `# Python3 program to replace all 'O's with``# 'X's if surrounded by 'X'` `# Size of given matrix is M x N``M ``=` `6``N ``=` `6` `# A recursive function to replace previous``# value 'prevV' at '(x, y)' and all surrounding``# values of (x, y) with new value 'newV'.``def` `floodFillUtil(mat, x, y, prevV, newV):` `    ``# Base Cases``    ``if` `(x < ``0` `or` `x >``=` `M ``or` `y < ``0` `or` `y >``=` `N):``        ``return` `    ``if` `(mat[x][y] !``=` `prevV):``        ``return` `    ``# Replace the color at (x, y)``    ``mat[x][y] ``=` `newV` `    ``# Recur for north, east, south and west``    ``floodFillUtil(mat, x ``+` `1``, y, prevV, newV)``    ``floodFillUtil(mat, x ``-` `1``, y, prevV, newV)``    ``floodFillUtil(mat, x, y ``+` `1``, prevV, newV)``    ``floodFillUtil(mat, x, y ``-` `1``, prevV, newV)` `# Returns size of maximum size subsquare``#  matrix surrounded by 'X'``def` `replaceSurrounded(mat):` `    ``# Step 1: Replace all 'O's with '-'``    ``for` `i ``in` `range``(M):``        ``for` `j ``in` `range``(N):``            ``if` `(mat[i][j] ``=``=` `'O'``):``                ``mat[i][j] ``=` `'-'` `    ``# Call floodFill for all '-'``    ``# lying on edges``     ``# Left Side``    ``for` `i ``in` `range``(M):``        ``if` `(mat[i][``0``] ``=``=` `'-'``):``            ``floodFillUtil(mat, i, ``0``, ``'-'``, ``'O'``)``    ` `    ``# Right side``    ``for` `i ``in` `range``(M):``        ``if` `(mat[i][N ``-` `1``] ``=``=` `'-'``):``            ``floodFillUtil(mat, i, N ``-` `1``, ``'-'``, ``'O'``)``    ` `    ``# Top side``    ``for` `i ``in` `range``(N):``        ``if` `(mat[``0``][i] ``=``=` `'-'``):``            ``floodFillUtil(mat, ``0``, i, ``'-'``, ``'O'``)``    ` `    ``# Bottom side``    ``for` `i ``in` `range``(N):``        ``if` `(mat[M ``-` `1``][i] ``=``=` `'-'``):``            ``floodFillUtil(mat, M ``-` `1``, i, ``'-'``, ``'O'``)` `    ``# Step 3: Replace all '-' with 'X'``    ``for` `i ``in` `range``(M):``        ``for` `j ``in` `range``(N):``            ``if` `(mat[i][j] ``=``=` `'-'``):``                ``mat[i][j] ``=` `'X'` `# Driver code``if` `__name__ ``=``=` `'__main__'``:` `    ``mat ``=` `[ [ ``'X'``, ``'O'``, ``'X'``, ``'O'``, ``'X'``, ``'X'` `],``            ``[ ``'X'``, ``'O'``, ``'X'``, ``'X'``, ``'O'``, ``'X'` `],``            ``[ ``'X'``, ``'X'``, ``'X'``, ``'O'``, ``'X'``, ``'X'` `],``            ``[ ``'O'``, ``'X'``, ``'X'``, ``'X'``, ``'X'``, ``'X'` `],``            ``[ ``'X'``, ``'X'``, ``'X'``, ``'O'``, ``'X'``, ``'O'` `],``            ``[ ``'O'``, ``'O'``, ``'X'``, ``'O'``, ``'O'``, ``'O'` `] ];` `    ``replaceSurrounded(mat)` `    ``for` `i ``in` `range``(M):``        ``print``(``*``mat[i])` `# This code is contributed by himanshu77`

## C#

 `// A C# program to replace``// all 'O's with 'X''s if``// surrounded by 'X'``using` `System;` `class` `GFG``{``    ``static` `int` `M = 6;``    ``static` `int` `N = 6;``    ``static` `void` `floodFillUtil(``char` `[,]mat, ``int` `x,``                              ``int` `y, ``char` `prevV,``                              ``char` `newV)``    ``{``        ``// Base cases``        ``if` `(x < 0 || x >= M ||``            ``y < 0 || y >= N)``            ``return``;``            ` `        ``if` `(mat[x, y] != prevV)``            ``return``;``    ` `        ``// Replace the color at (x, y)``        ``mat[x, y] = newV;``     ` `        ``// Recur for north,``        ``// east, south and west``        ``floodFillUtil(mat, x + 1, y,``                       ``prevV, newV);``        ``floodFillUtil(mat, x - 1, y,``                       ``prevV, newV);``        ``floodFillUtil(mat, x, y + 1,``                       ``prevV, newV);``        ``floodFillUtil(mat, x, y - 1,``                       ``prevV, newV);``    ``}``    ` `    ``// Returns size of maximum``    ``// size subsquare matrix``    ``// surrounded by 'X'``    ``static` `void` `replaceSurrounded(``char` `[,]mat)``    ``{``        ` `    ``// Step 1: Replace``    ``// all 'O' with '-'``    ``for` `(``int` `i = 0; i < M; i++)``        ``for` `(``int` `j = 0; j < N; j++)``            ``if` `(mat[i, j] == ``'O'``)``                ``mat[i, j] = ``'-'``;``    ` `    ``// Call floodFill for``    ``// all '-' lying on edges``    ``for` `(``int` `i = 0; i < M; i++) ``// Left side``        ``if` `(mat[i, 0] == ``'-'``)``            ``floodFillUtil(mat, i, 0,``                          ``'-'``, ``'O'``);``    ``for` `(``int` `i = 0; i < M; i++) ``// Right side``        ``if` `(mat[i, N - 1] == ``'-'``)``            ``floodFillUtil(mat, i, N - 1,``                          ``'-'``, ``'O'``);``    ``for` `(``int` `i = 0; i < N; i++) ``// Top side``        ``if` `(mat[0, i] == ``'-'``)``            ``floodFillUtil(mat, 0, i,``                          ``'-'``, ``'O'``);``    ``for` `(``int` `i = 0; i < N; i++) ``// Bottom side``        ``if` `(mat[M - 1, i] == ``'-'``)``            ``floodFillUtil(mat, M - 1,``                          ``i, ``'-'``, ``'O'``);``    ` `    ``// Step 3: Replace``    ``// all '-' with 'X'``    ``for` `(``int` `i = 0; i < M; i++)``        ``for` `(``int` `j = 0; j < N; j++)``            ``if` `(mat[i, j] == ``'-'``)``                ``mat[i, j] = ``'X'``;``    ``}``    ` `    ``// Driver Code``    ``public` `static` `void` `Main ()``    ``{``        ``char` `[,]mat = ``new` `char``[,]``                        ``{{``'X'``, ``'O'``, ``'X'``,``                          ``'O'``, ``'X'``, ``'X'``},``                         ``{``'X'``, ``'O'``, ``'X'``,``                          ``'X'``, ``'O'``, ``'X'``},``                         ``{``'X'``, ``'X'``, ``'X'``,``                          ``'O'``, ``'X'``, ``'X'``},``                         ``{``'O'``, ``'X'``, ``'X'``,``                          ``'X'``, ``'X'``, ``'X'``},``                         ``{``'X'``, ``'X'``, ``'X'``,``                          ``'O'``, ``'X'``, ``'O'``},``                         ``{``'O'``, ``'O'``, ``'X'``,``                          ``'O'``, ``'O'``, ``'O'``}};``                        ` `        ``replaceSurrounded(mat);``    ` `        ``for` `(``int` `i = 0; i < M; i++)``        ``{``            ``for` `(``int` `j = 0; j < N; j++)``                ``Console.Write(mat[i, j] + ``" "``);``                ` `            ``Console.WriteLine(``""``);``        ``}``    ``}``}` `// This code is contributed``// by shiv_bhakt`

## Javascript

 ``

## PHP

 `= ``\$GLOBALS``[``'M'``] ||``        ``\$y` `< 0 || ``\$y` `>= ``\$GLOBALS``[``'N'``])``        ``return``;``    ``if` `(``\$mat``[``\$x``][``\$y``] != ``\$prevV``)``        ``return``;` `    ``// Replace the color at (x, y)``    ``\$mat``[``\$x``][``\$y``] = ``\$newV``;` `    ``// Recur for north,``    ``// east, south and west``    ``floodFillUtil(``\$mat``, ``\$x` `+ 1, ``\$y``, ``\$prevV``, ``\$newV``);``    ``floodFillUtil(``\$mat``, ``\$x` `- 1, ``\$y``, ``\$prevV``, ``\$newV``);``    ``floodFillUtil(``\$mat``, ``\$x``, ``\$y` `+ 1, ``\$prevV``, ``\$newV``);``    ``floodFillUtil(``\$mat``, ``\$x``, ``\$y` `- 1, ``\$prevV``, ``\$newV``);``}` `// Returns size of maximum``// size subsquare matrix``// surrounded by 'X'``function` `replaceSurrounded(&``\$mat``)``{``    ` `// Step 1: Replace all 'O' with '-'``for` `(``\$i` `= 0; ``\$i` `< ``\$GLOBALS``[``'M'``]; ``\$i``++)``    ``for` `(``\$j` `= 0; ``\$j` `< ``\$GLOBALS``[``'N'``]; ``\$j``++)``        ``if` `(``\$mat``[``\$i``][``\$j``] == ``'O'``)``            ``\$mat``[``\$i``][``\$j``] = ``'-'``;` `// Call floodFill for all``// '-' lying on edges``for` `(``\$i` `= 0;``     ``\$i` `< ``\$GLOBALS``[``'M'``]; ``\$i``++) ``// Left side``    ``if` `(``\$mat``[``\$i``][0] == ``'-'``)``        ``floodFillUtil(``\$mat``, ``\$i``, 0, ``'-'``, ``'O'``);``        ` `for` `(``\$i` `= 0; ``\$i` `< ``\$GLOBALS``[``'M'``]; ``\$i``++) ``// Right side``    ``if` `(``\$mat``[``\$i``][``\$GLOBALS``[``'N'``] - 1] == ``'-'``)``        ``floodFillUtil(``\$mat``, ``\$i``,``                      ``\$GLOBALS``[``'N'``] - 1, ``'-'``, ``'O'``);``        ` `for` `(``\$i` `= 0; ``\$i` `< ``\$GLOBALS``[``'N'``]; ``\$i``++) ``// Top side``    ``if` `(``\$mat``[0][``\$i``] == ``'-'``)``        ``floodFillUtil(``\$mat``, 0, ``\$i``, ``'-'``, ``'O'``);``        ` `for` `(``\$i` `= 0; ``\$i` `< ``\$GLOBALS``[``'N'``]; ``\$i``++) ``// Bottom side``    ``if` `(``\$mat``[``\$GLOBALS``[``'M'``] - 1][``\$i``] == ``'-'``)``        ``floodFillUtil(``\$mat``, ``\$GLOBALS``[``'M'``] - 1,``                            ``\$i``, ``'-'``, ``'O'``);` `// Step 3: Replace all '-' with 'X'``for` `(``\$i` `= 0; ``\$i` `< ``\$GLOBALS``[``'M'``]; ``\$i``++)``    ``for` `(``\$j` `= 0; ``\$j` `< ``\$GLOBALS``[``'N'``]; ``\$j``++)``        ``if` `(``\$mat``[``\$i``][``\$j``] == ``'-'``)``            ``\$mat``[``\$i``][``\$j``] = ``'X'``;` `}` `// Driver Code``\$mat` `= ``array``(``array``(``'X'``, ``'O'``, ``'X'``, ``'O'``, ``'X'``, ``'X'``),``             ``array``(``'X'``, ``'O'``, ``'X'``, ``'X'``, ``'O'``, ``'X'``),``             ``array``(``'X'``, ``'X'``, ``'X'``, ``'O'``, ``'X'``, ``'X'``),``             ``array``(``'O'``, ``'X'``, ``'X'``, ``'X'``, ``'X'``, ``'X'``),``             ``array``(``'X'``, ``'X'``, ``'X'``, ``'O'``, ``'X'``, ``'O'``),``             ``array``(``'O'``, ``'O'``, ``'X'``, ``'O'``, ``'O'``, ``'O'``));``replaceSurrounded(``\$mat``);` `for` `(``\$i` `= 0; ``\$i` `< ``\$GLOBALS``[``'M'``]; ``\$i``++)``{``    ``for` `(``\$j` `= 0; ``\$j` `< ``\$GLOBALS``[``'N'``]; ``\$j``++)``        ``echo` `\$mat``[``\$i``][``\$j``].``" "``;``    ``echo` `"\n"``;``}` `// This code is contributed by ChitraNayal``?>`

Output

```X O X O X X
X O X X X X
X X X X X X
O X X X X X
X X X O X O
O O X O O O

```

Time Complexity of the above solution is O(MN). Note that every element of matrix is processed at most three times.
Auxiliary Space: O(M x N), as implicit stack is used due to recursive call

## OPTIMIZED APPROACH

Intuition:

1. Traverse the given matrix and replace all ‘O’ with a special character ‘&’.
2. Traverse four edges of given matrix and call dfs(‘&’, ‘O’) for every ‘&’ on edges. The remaining ‘&’ are the characters that indicate ‘O’s (in the original matrix) to be replaced by ‘X’.
3. Traverse the matrix and replace all ‘&’s with ‘X’s.

Implementation

## Java

 `// A Java program to replace``// all 'O's with 'X''s if``// surrounded by 'X'` `import` `java.io.*;` `class` `GFG {``    ``static` `char``[][] fill(``int` `n, ``int` `m, ``char` `a[][])``    ``{``        ``// code here``        ``for` `(``int` `i = ``0``; i < n; i++) {``            ``for` `(``int` `j = ``0``; j < m; j++) {``                ``if` `((i == ``0` `|| i == n - ``1` `|| j == ``0``                     ``|| j == m - ``1``)``                    ``&& a[i][j] == ``'O'``)``                    ``dfs(a, n, m, i, j);``            ``}``        ``}``        ``for` `(``int` `i = ``0``; i < n; i++) {``            ``for` `(``int` `j = ``0``; j < m; j++) {``                ``if` `(a[i][j] == ``'O'``)``                    ``a[i][j] = ``'X'``;``                ``else` `if` `(a[i][j] == ``'\$'``)``                    ``a[i][j] = ``'O'``;``            ``}``        ``}``        ``return` `a;``    ``}``    ``static` `void` `dfs(``char` `a[][], ``int` `n, ``int` `m, ``int` `i, ``int` `j)``    ``{``        ``if` `(i < ``0` `|| i >= n || j < ``0` `|| j >= m``            ``|| a[i][j] == ``'X'``)``            ``return``;` `        ``if` `(a[i][j] == ``'O'``) {``            ``a[i][j] = ``'\$'``;``            ``dfs(a, n, m, i + ``1``, j);``            ``dfs(a, n, m, i - ``1``, j);``            ``dfs(a, n, m, i, j - ``1``);``            ``dfs(a, n, m, i, j + ``1``);``        ``}``    ``}``    ``public` `static` `void` `main(String[] args)``    ``{``        ``char``[][] mat = { { ``'X'``, ``'O'``, ``'X'``, ``'O'``, ``'X'``, ``'X'` `},``                         ``{ ``'X'``, ``'O'``, ``'X'``, ``'X'``, ``'O'``, ``'X'` `},``                         ``{ ``'X'``, ``'X'``, ``'X'``, ``'O'``, ``'X'``, ``'X'` `},``                         ``{ ``'O'``, ``'X'``, ``'X'``, ``'X'``, ``'X'``, ``'X'` `},``                         ``{ ``'X'``, ``'X'``, ``'X'``, ``'O'``, ``'X'``, ``'O'` `},``                         ``{ ``'O'``, ``'O'``, ``'X'``, ``'O'``, ``'O'``, ``'O'` `} };` `        ``int` `N = mat.length;``        ``int` `M = mat[``0``].length;``        ``fill(N, M, mat);` `        ``for` `(``int` `i = ``0``; i < N; i++) {``            ``for` `(``int` `j = ``0``; j < M; j++)``                ``System.out.print(mat[i][j] + ``" "``);` `            ``System.out.println(``""``);``        ``}``    ``}``}``// This code is contributed by Raunak Singh`

## Python3

 `def` `fill(n, m, a):``    ``# Iterate through the edges of the matrix``    ``for` `i ``in` `range``(n):``        ``for` `j ``in` `range``(m):``            ``if` `(i ``=``=` `0` `or` `i ``=``=` `n ``-` `1` `or` `j ``=``=` `0``                ``or` `j ``=``=` `m ``-` `1``) ``and` `a[i][j] ``=``=` `'O'``:``                ``dfs(a, n, m, i, j)``    ` `    ``# Convert '\$' back to 'O' and 'O' to 'X'``    ``for` `i ``in` `range``(n):``        ``for` `j ``in` `range``(m):``            ``if` `a[i][j] ``=``=` `'O'``:``                ``a[i][j] ``=` `'X'``            ``elif` `a[i][j] ``=``=` `'\$'``:``                ``a[i][j] ``=` `'O'``    ``return` `a` `def` `dfs(a, n, m, i, j):``    ``if` `i < ``0` `or` `i >``=` `n ``or` `j < ``0` `or` `j >``=` `m ``or` `a[i][j] ``=``=` `'X'``:``        ``return` `    ``if` `a[i][j] ``=``=` `'O'``:``        ``a[i][j] ``=` `'\$'``        ``dfs(a, n, m, i ``+` `1``, j)``        ``dfs(a, n, m, i ``-` `1``, j)``        ``dfs(a, n, m, i, j ``-` `1``)``        ``dfs(a, n, m, i, j ``+` `1``)` `if` `__name__ ``=``=` `"__main__"``:``    ``mat ``=` `[[``'X'``, ``'O'``, ``'X'``, ``'O'``, ``'X'``, ``'X'``],``           ``[``'X'``, ``'O'``, ``'X'``, ``'X'``, ``'O'``, ``'X'``],``           ``[``'X'``, ``'X'``, ``'X'``, ``'O'``, ``'X'``, ``'X'``],``           ``[``'O'``, ``'X'``, ``'X'``, ``'X'``, ``'X'``, ``'X'``],``           ``[``'X'``, ``'X'``, ``'X'``, ``'O'``, ``'X'``, ``'O'``],``           ``[``'O'``, ``'O'``, ``'X'``, ``'O'``, ``'O'``, ``'O'``]]` `    ``N ``=` `len``(mat)``    ``M ``=` `len``(mat[``0``])``    ``fill(N, M, mat)` `    ``for` `i ``in` `range``(N):``        ``for` `j ``in` `range``(M):``            ``print``(mat[i][j], end``=``" "``)``        ``print``("")`

Output

```X O X O X X
X O X X X X
X X X X X X
O X X X X X
X X X O X O
O O X O O O

```

Time Complexity: O(N*M)
Space Complexity: O(1)

Approach:(Using DFS)

The given code aims to replace all ‘O’s in a matrix with ‘X’ if they are surrounded by ‘X’s. The algorithm follows a depth-first search (DFS) approach to identify and mark the ‘O’s that are surrounded.

The main steps of the algorithm are as follows:

1. Define a flood-fill utility function, floodFillUtil, which takes the matrix, current position (x, y), the previous value (‘O’ or ‘-‘), and the new value (‘-‘ or ‘X’). This function recursively explores the neighboring cells and replaces the previous value with the new value.
2. Initialize the matrix traversal:    Replace all ‘O’s with ‘-‘.
3. Traverse the edges of the matrix and call the floodFillUtil function for each ‘-‘ encountered. This step marks all the ‘-‘ connected to the edges and not surrounded by ‘X’s as ‘O’. This ensures that any ‘O’ not connected to an edge is surrounded by ‘X’s.
4. After the traversal, all remaining ‘O’s in the matrix are the ones that are surrounded by ‘X’s. Replace these ‘O’s with ‘X’ and restore the ‘-‘ to ‘O’.
5. Print the modified matrix.

The intuition behind the algorithm is to identify the ‘O’s that are not surrounded by ‘X’s by starting from the edges of the matrix. By performing a flood-fill traversal from the edges and marking the connected ‘-‘ cells as ‘O’, we can identify the ‘O’s that are not surrounded. The remaining ‘O’s are the ones surrounded by ‘X’s, which are then replaced with ‘X’.

## C++

 `#include``using` `namespace` `std;` `#define M 6``#define N 6` `void` `floodFillUtil(``char` `mat[][N], ``int` `x, ``int` `y, ``char` `prevV, ``char` `newV)``{``    ``if` `(x < 0 || x >= M || y < 0 || y >= N)``        ``return``;``    ``if` `(mat[x][y] != prevV)``        ``return``;` `    ``mat[x][y] = newV;` `    ``floodFillUtil(mat, x+1, y, prevV, newV);``    ``floodFillUtil(mat, x-1, y, prevV, newV);``    ``floodFillUtil(mat, x, y+1, prevV, newV);``    ``floodFillUtil(mat, x, y-1, prevV, newV);``}` `void` `replaceSurrounded(``char` `mat[][N])``{``    ``for` `(``int` `i=0; i

## Javascript

 `// JavaScript Program for the above approach``const M = 6;``const N = 6;` `// Recursive function to perform flood fill``function` `floodFillUtil(mat, x, y, prevV, newV) {``    ``if` `(x < 0 || x >= M || y < 0 || y >= N) {``        ``return``;``    ``}``    ``if` `(mat[x][y] !== prevV) {``        ``return``;``    ``}` `    ``mat[x][y] = newV;` `    ``floodFillUtil(mat, x + 1, y, prevV, newV);``    ``floodFillUtil(mat, x - 1, y, prevV, newV);``    ``floodFillUtil(mat, x, y + 1, prevV, newV);``    ``floodFillUtil(mat, x, y - 1, prevV, newV);``}` `// Function to replace surrounded 'O's with 'X's``function` `replaceSurrounded(mat) {``    ``// Step 1: Perform flood fill from the boundary 'O's to``    ``// mark connected 'O's with '-'``    ``for` `(let i = 0; i < M; i++) {``        ``for` `(let j = 0; j < N; j++) {``            ``if` `(i === 0 || i === M - 1 || j === 0 || j === N - 1) {``                ``if` `(mat[i][j] === ``'O'``) {``                    ``floodFillUtil(mat, i, j, ``'O'``, ``'-'``);``                ``}``            ``}``        ``}``    ``}` `    ``// Step 2: Replace the remaining 'O's with 'X's, and``   ``// convert '-' back to 'O's``    ``for` `(let i = 0; i < M; i++) {``        ``for` `(let j = 0; j < N; j++) {``            ``if` `(mat[i][j] === ``'O'``) {``                ``mat[i][j] = ``'X'``;``            ``} ``else` `if` `(mat[i][j] === ``'-'``) {``                ``mat[i][j] = ``'O'``;``            ``}``        ``}``    ``}``}` `// Example usage``const mat = [[``'X'``, ``'O'``, ``'X'``, ``'O'``, ``'X'``, ``'X'``],``             ``[``'X'``, ``'O'``, ``'X'``, ``'X'``, ``'O'``, ``'X'``],``             ``[``'X'``, ``'X'``, ``'X'``, ``'O'``, ``'X'``, ``'X'``],``             ``[``'O'``, ``'X'``, ``'X'``, ``'X'``, ``'X'``, ``'X'``],``             ``[``'X'``, ``'X'``, ``'X'``, ``'O'``, ``'X'``, ``'O'``],``             ``[``'O'``, ``'O'``, ``'X'``, ``'O'``, ``'O'``, ``'O'``]];` `// Call the function to replace surrounded 'O's``replaceSurrounded(mat);` `// Print the updated matrix``for` `(let i = 0; i < M; i++) {``    ``for` `(let j = 0; j < N; j++) {``        ``console.log(mat[i][j] + ``" "``);``    ``}``    ``console.log(``""``);``}``// This code is contributed by Kanchan Agarwal`

Output

```X O X O X X
X O X X X X
X X X X X X
O X X X X X
X X X O X O
O O X O O O

```

Time Complexity: O(N*M)
Auxiliary Space: O(1)