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 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.
Algorithm:
- Traverse the given matrix and replace all 'O' with a special character '-'.
- 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'.
- Traverse the matrix and replace all '-'s with 'X's.
Illustration:
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<iostream>
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<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 program to test above function
int main()
{
char mat[][N] = {{'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++)
cout << mat[i][j] << " ";
cout << endl;
}
return 0;
}
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
<script>
// A Javascript program to replace
// all 'O's with 'X''s if
// surrounded by 'X'
let M = 6;
let N = 6;
function floodFillUtil(mat,x,y,prevV,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'
function replaceSurrounded(mat)
{
// Step 1: Replace
// all 'O' with '-'
for (let i = 0; i < M; i++)
for (let j = 0; j < N; j++)
if (mat[i][j] == 'O')
mat[i][j] = '-';
// Call floodFill for
// all '-' lying on edges
for (let i = 0; i < M; i++) // Left side
if (mat[i][0] == '-')
floodFillUtil(mat, i, 0,
'-', 'O');
for (let i = 0; i < M; i++) // Right side
if (mat[i][N - 1] == '-')
floodFillUtil(mat, i, N - 1,
'-', 'O');
for (let i = 0; i < N; i++) // Top side
if (mat[0][i] == '-')
floodFillUtil(mat, 0, i,
'-', 'O');
for (let 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 (let i = 0; i < M; i++)
for (let j = 0; j < N; j++)
if (mat[i][j] == '-')
mat[i][j] = 'X';
}
// Driver Code
let 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 (let i = 0; i < M; i++)
{
for (let j = 0; j < N; j++)
document.write(mat[i][j] + " ");
document.write("<br>");
}
// This code is contributed by rag2127
</script>
PHP
<?php
// A PHP 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'.
function floodFillUtil(&$mat, $x, $y,
$prevV, $newV)
{
// Base cases
if ($x < 0 || $x >= $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
?>
OutputX 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(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
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read
Selection Sort Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read