# Replace specified matrix elements such that no two adjacent elements are equal

• Difficulty Level : Hard
• Last Updated : 24 May, 2021

Given a matrix arr[][] of dimensions N * M, consisting of ‘O’ or ‘F’, where ‘O’ denotes obstacles and ‘F’ denotes free spaces, the task is to replace all ‘F’s in the given matrix by either ‘1’ or ‘2’, such that no two adjacent cells have the same value.

Examples:

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

Input: N = 4, M = 4, arr[][] = {{‘F’, ‘F’, ‘F’, ‘F’}, {‘F’, ‘O’, ‘F’, ‘F’}, {‘F’, ‘F’, ‘O’, ‘F’}, {‘F’, ‘F’, ‘F’, ‘F’}}
Output:
1 2 1 2
2 O 2 1
1 2 O 2
2 1 2 1

Input: N = 1, M = 1, arr[][] = {{‘O’}}
Output:

Naive Approach: The simplest approach to solve the problem is to use Backtracking, similar to the Sudoku problem. But, instead of placing N different values in a given position, either 1 or 2 is required to be placed on cells containing ‘F’ such that no two adjacent elements are equal to each other. Follow the steps below to solve the problem:

• Create a function to check if the given position in the matrix is valid or not.
• If the end of the matrix has been reached, i.e. i = N and j = M, then return True.
• Otherwise, if the current index is a free space, i.e arr[i][j]==’F’ , then fill the index with either ‘1’ or ‘2’. If any cell is found to be invalid, i.e. any of its adjacent cells has the same value, then print “No”.
• After complete traversal of the matrix, if all the ‘F’s were replaced such that no adjacent matrix elements are same, then print “Yes”.

Below is the implementation of the above approach:

## C++

 `// C++ program for the above approach` `#include ``using` `namespace` `std;` `// Function to check if current``// position is safe or not``bool` `issafe(vector >& v, ``int` `i,``            ``int` `j, ``int` `n, ``int` `m, ``char` `ch)``{``    ``// Directions for adjacent cells``    ``int` `rowN[] = { 1, -1, 0, 0 };``    ``int` `colN[] = { 0, 0, 1, -1 };` `    ``for` `(``int` `k = 0; k < 4; k++) {` `        ``// Check if any adjacent cell is same``        ``if` `(i + rowN[k] >= 0 && i + rowN[k] < n``            ``&& j + colN[k] >= 0 && j + colN[k] < m``            ``&& v[i + rowN[k]][j + colN[k]] == ch) {``            ``return` `false``;``        ``}``    ``}` `    ``// Current index is valid``    ``return` `true``;``}` `// Recursive function for backtracking``bool` `place(vector >& v,``           ``int` `n, ``int` `m)``{``    ``int` `i, j;``    ``for` `(i = 0; i < n; i++) {``        ``for` `(j = 0; j < m; j++) {` `            ``// Free cell``            ``if` `(v[i][j] == ``'F'``) {``                ``break``;``            ``}``        ``}``        ``if` `(j != m) {``            ``break``;``        ``}``    ``}` `    ``// All positions covered``    ``if` `(i == n && j == m) {``        ``return` `true``;``    ``}` `    ``// If position is valid for 1``    ``if` `(issafe(v, i, j, n, m, ``'1'``)) {``        ``v[i][j] = ``'1'``;``        ``if` `(place(v, n, m)) {``            ``return` `true``;``        ``}``        ``v[i][j] = ``'F'``;``    ``}` `    ``// If position is valid for 2``    ``if` `(issafe(v, i, j, n, m, ``'2'``)) {``        ``v[i][j] = ``'2'``;` `        ``// Recursive call for next``        ``// unoccupied position``        ``if` `(place(v, n, m)) {``            ``return` `true``;``        ``}` `        ``// If above conditions fails``        ``v[i][j] = ``'F'``;``    ``}``    ``return` `false``;``}` `// Function to print valid matrix``void` `printMatrix(vector > arr,``                 ``int` `n, ``int` `m)``{` `    ``place(arr, n, m);``    ``for` `(``int` `i = 0; i < n; i++) {``        ``for` `(``int` `j = 0; j < m; j++) {``            ``cout << arr[i][j];``        ``}``        ``cout << endl;``    ``}``}` `// Driver Code``int` `main()``{` `    ``// Given matrix``    ``vector > arr = {``        ``{ ``'F'``, ``'F'``, ``'F'``, ``'F'` `},``        ``{ ``'F'``, ``'O'``, ``'F'``, ``'F'` `},``        ``{ ``'F'``, ``'F'``, ``'O'``, ``'F'` `},``        ``{ ``'F'``, ``'F'``, ``'F'``, ``'F'` `},``    ``};` `    ``// Give dimensions``    ``int` `n = 4, m = 4;` `    ``// Function call``    ``printMatrix(arr, n, m);` `    ``return` `0;``}`

## Java

 `// Java program for the above approach``import` `java.io.*;` `class` `GFG {``    ``public` `static` `boolean` `issafe(``char` `v[][], ``int` `i,``            ``int` `j, ``int` `n, ``int` `m, ``char` `ch)``    ``{``        ``// Directions for adjacent cells``        ``int` `rowN[] = { ``1``, -``1``, ``0``, ``0` `};``        ``int` `colN[] = { ``0``, ``0``, ``1``, -``1` `};` `        ``for` `(``int` `k = ``0``; k < ``4``; k++) {` `            ``// Check if any adjacent cell is same``            ``if` `(i + rowN[k] >= ``0` `&& i + rowN[k] < n``                ``&& j + colN[k] >= ``0` `&& j + colN[k] < m``                ``&& v[i + rowN[k]][j + colN[k]] == ch) {``                ``return` `false``;``            ``}``        ``}` `        ``// Current index is valid``        ``return` `true``;``    ``}` `    ``// Recursive function for backtracking``    ``public` `static` `boolean` `place(``char` `v[][],``           ``int` `n, ``int` `m)``    ``{``        ``int` `i=``0``, j=``0``;``        ``for` `(i = ``0``; i < n; i++) {``            ``for` `(j = ``0``; j < m; j++) {``    ` `                ``// Free cell``                ``if` `(v[i][j] == ``'F'``) {``                    ``break``;``                ``}``            ``}``            ``if` `(j != m) {``                ``break``;``            ``}``        ``}` `        ``// All positions covered``        ``if` `(i == n && j == m) {``            ``return` `true``;``        ``}` `        ``// If position is valid for 1``        ``if` `(issafe(v, i, j, n, m, ``'1'``)) {``            ``v[i][j] = ``'1'``;``            ``if` `(place(v, n, m)) {``                ``return` `true``;``            ``}``            ``v[i][j] = ``'F'``;``        ``}` `        ``// If position is valid for 2``        ``if` `(issafe(v, i, j, n, m, ``'2'``)) {``            ``v[i][j] = ``'2'``;` `            ``// Recursive call for next``            ``// unoccupied position``            ``if` `(place(v, n, m)) {``                ``return` `true``;``            ``}` `            ``// If above conditions fails``            ``v[i][j] = ``'F'``;``        ``}``        ``return` `false``;``    ``}``    ``// Function to print valid matrix``    ``public` `static` `void` `printMatrix(``char` `arr[][],``                 ``int` `n, ``int` `m)``    ``{``        ``place(arr, n, m);``        ``for` `(``int` `i = ``0``; i < n; i++) {``            ``for` `(``int` `j = ``0``; j < m; j++) {``                ``System.out.print(arr[i][j]);``            ``}``            ``System.out.println();``        ``}``    ``}``  ` `    ``// Driver Code``    ``public` `static` `void` `main (String[] args) {``        ``char` `arr[][] = {``        ``{ ``'F'``, ``'F'``, ``'F'``, ``'F'` `},``        ``{ ``'F'``, ``'O'``, ``'F'``, ``'F'` `},``        ``{ ``'F'``, ``'F'``, ``'O'``, ``'F'` `},``        ``{ ``'F'``, ``'F'``, ``'F'``, ``'F'` `},``                            ``};` `        ``// Give dimensions``        ``int` `n = ``4``, m = ``4``;` `        ``// Function call``        ``printMatrix(arr, n, m);``    ``}``}`

## C#

 `// C# program for the above approach``using` `System;` `class` `GFG{` `// Function to check if current``// position is safe or not   ``public` `static` `bool` `issafe(``char``[,] v, ``int` `i,``                              ``int` `j, ``int` `n,``                              ``int` `m, ``char` `ch)``{``    ` `    ``// Directions for adjacent cells``    ``int``[] rowN = { 1, -1, 0, 0 };``    ``int``[] colN = { 0, 0, 1, -1 };` `    ``for``(``int` `k = 0; k < 4; k++)``    ``{``        ` `        ``// Check if any adjacent cell is same``        ``if` `(i + rowN[k] >= 0 && i + rowN[k] < n &&``            ``j + colN[k] >= 0 && j + colN[k] < m &&``            ``v[(i + rowN[k]), (j + colN[k])] == ch)``        ``{``            ``return` `false``;``        ``}``    ``}` `    ``// Current index is valid``    ``return` `true``;``}` `// Recursive function for backtracking``public` `static` `bool` `place(``char``[,] v,``                         ``int` `n, ``int` `m)``{``    ``int` `i = 0, j = 0;``    ` `    ``for``(i = 0; i < n; i++)``    ``{``        ``for``(j = 0; j < m; j++)``        ``{``            ` `            ``// Free cell``            ``if` `(v[i, j] == ``'F'``)``            ``{``                ``break``;``            ``}``        ``}``        ``if` `(j != m)``        ``{``            ``break``;``        ``}``    ``}` `    ``// All positions covered``    ``if` `(i == n && j == m)``    ``{``        ``return` `true``;``    ``}` `    ``// If position is valid for 1``    ``if` `(issafe(v, i, j, n, m, ``'1'``))``    ``{``        ``v[i, j] = ``'1'``;``        ` `        ``if` `(place(v, n, m))``        ``{``            ``return` `true``;``        ``}``        ``v[i, j] = ``'F'``;``    ``}` `    ``// If position is valid for 2``    ``if` `(issafe(v, i, j, n, m, ``'2'``))``    ``{``        ``v[i, j] = ``'2'``;` `        ``// Recursive call for next``        ``// unoccupied position``        ``if` `(place(v, n, m))``        ``{``            ``return` `true``;``        ``}` `        ``// If above conditions fails``        ``v[i, j] = ``'F'``;``    ``}``    ``return` `false``;``}` `// Function to print valid matrix``public` `static` `void` `printMatrix(``char``[,] arr,``                               ``int` `n, ``int` `m)``{``    ``place(arr, n, m);``    ` `    ``for``(``int` `i = 0; i < n; i++)``    ``{``        ``for``(``int` `j = 0; j < m; j++)``        ``{``            ``Console.Write(arr[i, j]);``        ``}``        ``Console.WriteLine();``    ``}``}` `// Driver Code``public` `static` `void` `Main()``{``    ``char``[,] arr = { { ``'F'``, ``'F'``, ``'F'``, ``'F'` `},``                    ``{ ``'F'``, ``'O'``, ``'F'``, ``'F'` `},``                    ``{ ``'F'``, ``'F'``, ``'O'``, ``'F'` `},``                    ``{ ``'F'``, ``'F'``, ``'F'``, ``'F'` `},};` `    ``// Give dimensions``    ``int` `n = 4, m = 4;` `    ``// Function call``    ``printMatrix(arr, n, m);``}``}` `// This code is contributed by susmitakundugoaldanga`

## Javascript

 ``

Output
```1212
2O21
12O2
2121```

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

Efficient Approach: The idea is to simply replace any ‘F’ by 1 if the parity of cell (i, j) is 1 i.e., (i + j) % 2 is 1. Otherwise, replace that ‘F’ by 2. Follow the steps below to solve the problem:

• Traverse the given matrix.
• For each cell (i, j) traversed, if cell arr[i][j] is equal to ‘F’ and (i + j) % 2 is equal to 1, assign arr[i][j] = 1. Otherwise, assign arr[i][j] = 2.

Below is the implementation of the above approach:

## C++

 `// C++ program for the above approach` `#include ``using` `namespace` `std;` `// Function to display the valid matrix``void` `print(vector > arr, ``int` `n, ``int` `m)``{` `    ``// Traverse the matrix``    ``for` `(``int` `i = 0; i < n; i++) {``        ``for` `(``int` `j = 0; j < m; j++) {``            ``char` `a = arr[i][j];` `            ``// If the current cell is a free``            ``// space and is even-indexed``            ``if` `((i + j) % 2 == 0 && a == ``'F'``) {``                ``arr[i][j] = ``'1'``;``            ``}``            ``// If the current cell is a free``            ``// space and is odd-indexed``            ``else` `if` `(a == ``'F'``) {``                ``arr[i][j] = ``'2'``;``            ``}``        ``}``    ``}` `    ``// Print the matrix``    ``for` `(``int` `i = 0; i < n; i++) {``        ``for` `(``int` `j = 0; j < m; j++) {``            ``cout << arr[i][j];``        ``}``        ``cout << endl;``    ``}``}` `// Driver Code``int` `main()``{` `    ``// Given N and M``    ``int` `n = 4, m = 4;` `    ``// Given matrix``    ``vector > arr = {``        ``{ ``'F'``, ``'F'``, ``'F'``, ``'F'` `},``        ``{ ``'F'``, ``'O'``, ``'F'``, ``'F'` `},``        ``{ ``'F'``, ``'F'``, ``'O'``, ``'F'` `},``        ``{ ``'F'``, ``'F'``, ``'F'``, ``'F'` `},``    ``};` `    ``// Function call``    ``print(arr, n, m);``    ``return` `0;``}`

## Java

 `// Java program for the above approach``import` `java.io.*;` `class` `GFG``{``    ``// Function to display the valid matrix``    ``public` `static` `void` `print(``char` `arr[][], ``int` `n, ``int` `m)``    ``{``        ``// Traverse the matrix``        ``for` `(``int` `i = ``0``; i < n; i++) {``            ``for` `(``int` `j = ``0``; j < m; j++) {``                ``char` `a = arr[i][j];` `                ``// If the current cell is a free``                ``// space and is even-indexed``                ``if` `((i + j) % ``2` `== ``0` `&& a == ``'F'``) {``                    ``arr[i][j] = ``'1'``;``                ``}``                ``// If the current cell is a free``                ``// space and is odd-indexed``                ``else` `if` `(a == ``'F'``) {``                    ``arr[i][j] = ``'2'``;``                ``}``            ``}``        ``}` `        ``// Print the matrix``        ``for` `(``int` `i = ``0``; i < n; i++) {``            ``for` `(``int` `j = ``0``; j < m; j++) {``                ``System.out.print(arr[i][j]);``            ``}``            ``System.out.println();``        ``}``    ``}``   ` `    ``// Driver Code``    ``public` `static` `void` `main (String[] args) {``        ``// Given N and M``        ``int` `n = ``4``, m = ``4``;` `        ``// Given matrix``        ``char` `arr[][] = {``                        ``{ ``'F'``, ``'F'``, ``'F'``, ``'F'` `},``                        ``{ ``'F'``, ``'O'``, ``'F'``, ``'F'` `},``                        ``{ ``'F'``, ``'F'``, ``'O'``, ``'F'` `},``                        ``{ ``'F'``, ``'F'``, ``'F'``, ``'F'` `}};` `        ``// Function call``        ``print(arr, n, m);``    ``}``}`

## Python3

 `# Python3 program for the above approach` `# Function to display the valid matrix``def` `Print``(arr, n, m):` `    ``# Traverse the matrix``    ``for` `i ``in` `range``(n):``        ``for` `j ``in` `range``(m):``            ``a ``=` `arr[i][j]` `            ``# If the current cell is a free``            ``# space and is even-indexed``            ``if` `((i ``+` `j) ``%` `2` `=``=` `0` `and` `a ``=``=` `'F'``) :``                ``arr[i][j] ``=` `'1'``            ` `            ``# If the current cell is a free``            ``# space and is odd-indexed``            ``elif` `(a ``=``=` `'F'``) :``                ``arr[i][j] ``=` `'2'` `    ``# Print the matrix``    ``for` `i ``in` `range``(n) :``        ``for` `j ``in` `range``(m) :``            ``print``(arr[i][j], end ``=` `"")``    ` `        ``print``()` `# Given N and M``n, m ``=` `4``, ``4` `# Given matrix``arr ``=` `[``    ``[ ``'F'``, ``'F'``, ``'F'``, ``'F'` `],``    ``[ ``'F'``, ``'O'``, ``'F'``, ``'F'` `],``    ``[ ``'F'``, ``'F'``, ``'O'``, ``'F'` `],``    ``[ ``'F'``, ``'F'``, ``'F'``, ``'F'` `]]` `# Function call``Print``(arr, n, m)` `# This code is contributed by divyeshrabadiya07`

## C#

 `// C# program for the above approach``using` `System;` `class` `GFG{``    ` `// Function to display the valid matrix``public` `static` `void` `print(``char``[,] arr, ``int` `n,``                                      ``int` `m)``{``    ` `    ``// Traverse the matrix``    ``for``(``int` `i = 0; i < n; i++)``    ``{``        ``for``(``int` `j = 0; j < m; j++)``        ``{``            ``char` `a = arr[i, j];` `            ``// If the current cell is a free``            ``// space and is even-indexed``            ``if` `((i + j) % 2 == 0 && a == ``'F'``)``            ``{``                ``arr[i, j] = ``'1'``;``            ``}``            ` `            ``// If the current cell is a free``            ``// space and is odd-indexed``            ``else` `if` `(a == ``'F'``)``            ``{``                ``arr[i, j] = ``'2'``;``            ``}``        ``}``    ``}` `    ``// Print the matrix``    ``for``(``int` `i = 0; i < n; i++)``    ``{``        ``for``(``int` `j = 0; j < m; j++)``        ``{``            ``Console.Write(arr[i, j]);``        ``}``        ``Console.WriteLine();``    ``}``}` `// Driver Code``public` `static` `void` `Main()``{``    ` `    ``// Given N and M``    ``int` `n = 4, m = 4;` `    ``// Given matrix``    ``char``[,] arr = { { ``'F'``, ``'F'``, ``'F'``, ``'F'` `},``                    ``{ ``'F'``, ``'O'``, ``'F'``, ``'F'` `},``                    ``{ ``'F'``, ``'F'``, ``'O'``, ``'F'` `},``                    ``{ ``'F'``, ``'F'``, ``'F'``, ``'F'` `}};` `    ``// Function call``    ``print(arr, n, m);``}``}` `// This code is contributed by sanjoy_62`

## Javascript

 ``

Output
```1212
2O21
12O2
2121```

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

My Personal Notes arrow_drop_up