Check if elements of a Binary Matrix can be made alternating

Given a 2D array grid[][] of size N * M, consisting of the characters β€œ1”, β€œ0”, and β€œ*”, where β€œ*” denotes an empty space and can be replaced by either a β€œ1” or a β€œ0”. The task is to fill the grid such that β€œ0” and β€œ1” occur alternatively and no two consecutive characters occur together, i.e. (101010) is valid and (101101) is not because two β€œ1” occurs simultaneously. If it is possible to do so, print Yes and the possible 2-D array. Otherwise, print No.

Examples:

Input: N = 4, M = 4 grid[][] = { {**10}, {****}, {****}, {**01}}
Output: Yes
1010
0101
1010
0101
Explanation: Create a grid with alternating β€œ1” and β€œ0” characters so the answer is Yes, followed by the filled characters.

Input: N = 4, M = 4, grid[][] = {{*1*0}, {****}, {**10}, {****}}
Output: No
Explanation: In the first row, 1 and 0 have one cell blank which can neither be filled with 1 nor 0.

Approach: There are only 2 possibilities for a possible 2-D array one, with starting 1 and one with starting 0. Generate both of them and check if any one of them matches with the given 2-D array grid[][]. Follow the steps below to solve the problem:

  • Define a function createGrid(char grid[][1001], bool is1, int N, int M) and perform the following tasks:
    • Iterate over the range [0, N] using the variable i and performing the following tasks:
      • Iterate over the range [0, M] using the variable j and performing the following tasks:
        • If is1 is true, then set grid[i][j] to β€˜0’ and set is1 to false.
        • Else, then set grid[i][j] to β€˜1’ and set is1 to true.
      • If M%2 is equal to 0, then set the value of is1 to not of is1.
  • Define a function testGrid(char testGrid[][1001], char Grid[][1001], int N, int M) and perform the following tasks:
    • Iterate over the range [0, N] using the variable i and performing the following tasks:
      • Iterate over the range [0, M] using the variable j and performing the following tasks:
        • If Grid[i][j] is not equal to β€˜*’ and testGrid[i][j] is not equal to Grid[i][j], then return false.
    • After performing the above steps, return the value of true as the answer.
  • Define a function printGrid(char grid[][1001], int N, int M) and perform the following tasks:
  • Initialize two 2-D arrays gridTest1[N][1001] and gridTest2[N][1001] to store the possible alternating grids.
  • Call the function createGrid(gridTest1, true, N, M) and createGrid(gridTest2, false, N, M) to form the possible alternating grids.
  • If the function testGrid(gridTest1, grid, N, M) returns true, then call the function printGrid(gridTest1, N, M) to print the grid as the answer.
  • Else If, the function testGrid(gridTest2, grid, N, M) returns true, then call the function printGrid(gridTest2, N, M) to print the grid as the answer.
  • Else, print No as the answer.

Below is the implementation of the above approach.

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to create the possible grids
void createGrid(char grid[][1001], bool is1,
                int N, int M)
{
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < M; j++) {
 
            if (is1) {
                grid[i][j] = '0';
                is1 = false;
            }
            else {
                grid[i][j] = '1';
                is1 = true;
            }
        }
        if (M % 2 == 0)
            is1 = !is1;
    }
}
 
// Function to test if any one of them
// matches with the given 2-D array
bool testGrid(char testGrid[][1001],
              char Grid[][1001],
              int N, int M)
{
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < M; j++) {
 
            if (Grid[i][j] != '*') {
 
                if (Grid[i][j] != testGrid[i][j]) {
                    return false;
                }
            }
        }
    }
    return true;
}
 
// Function to print the grid, if possible
void printGrid(char grid[][1001], int N, int M)
{
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < M; j++) {
            cout << grid[i][j] << " ";
        }
        cout << endl;
    }
}
 
// Function to check if the grid
// can be made alternating or not
void findPossibleGrid(int N, int M,
                      char grid[][1001])
{
    // Grids to store the possible grids
    char gridTest1[N][1001], gridTest2[N][1001];
 
    createGrid(gridTest1, true, N, M);
 
    createGrid(gridTest2, false, N, M);
 
    if (testGrid(gridTest1, grid, N, M)) {
 
        cout << "Yes\n";
        printGrid(gridTest1, N, M);
    }
    else if (testGrid(gridTest2, grid, N, M)) {
 
        cout << "Yes\n";
        printGrid(gridTest2, N, M);
    }
    else {
        cout << "No\n";
    }
}
 
// Driver Code
int main()
{
    int N = 4, M = 4;
    char grid[][1001] = { { '*', '*', '1', '0' },
                          { '*', '*', '*', '*' },
                          { '*', '*', '*', '*' },
                          { '*', '*', '0', '1' } };
 
    findPossibleGrid(N, M, grid);
 
    return 0;
}


Java




// Java program for the above approach
import java.io.*;
 
class GFG{
     
// Function to create the possible grids
public static void createGrid(char[][] grid,
                              boolean is1,
                              int N, int M)
{
    for(int i = 0; i < N; i++)
    {
        for(int j = 0; j < M; j++)
        {
            if (is1)
            {
                grid[i][j] = '0';
                is1 = false;
            }
            else
            {
                grid[i][j] = '1';
                is1 = true;
            }
        }
        if (M % 2 == 0)
            is1 = !is1;
    }
}
 
// Function to test if any one of them
// matches with the given 2-D array
public static boolean testGrid(char[][] testGrid,
                               char[][] Grid, int N,
                               int M)
{
    for(int i = 0; i < N; i++)
    {
        for(int j = 0; j < M; j++)
        {
            if (Grid[i][j] != '*')
            {
                if (Grid[i][j] != testGrid[i][j])
                {
                    return false;
                }
            }
        }
    }
    return true;
}
 
// Function to print the grid, if possible
public static void printGrid(char[][] grid, int N,
                             int M)
{
    for(int i = 0; i < N; i++)
    {
        for(int j = 0; j < M; j++)
        {
            System.out.print(grid[i][j] + " ");
        }
        System.out.println();
    }
}
 
// Function to check if the grid
// can be made alternating or not
public static void findPossibleGrid(int N, int M,
                                    char[][] grid)
{
     
    // Grids to store the possible grids
    char[][] gridTest1 = new char[N][1001];
    char[][] gridTest2 = new char[N][1001];
 
    createGrid(gridTest1, true, N, M);
    createGrid(gridTest2, false, N, M);
 
    if (testGrid(gridTest1, grid, N, M))
    {
        System.out.println("Yes");
        printGrid(gridTest1, N, M);
    }
    else if (testGrid(gridTest2, grid, N, M))
    {
        System.out.println("Yes");
        printGrid(gridTest2, N, M);
    }
    else
    {
        System.out.println("No");
    }
}
 
// Driver code
public static void main(String[] args)
{
    int N = 4, M = 4;
    char[][] grid = { { '*', '*', '1', '0' },
                      { '*', '*', '*', '*' },
                      { '*', '*', '*', '*' },
                      { '*', '*', '0', '1' } };
 
    findPossibleGrid(N, M, grid);
}
}
 
// This code is contributed by maddler


Python3




# python 3 program for the above approach
 
# Function to create the possible grids
def createGrid(grid, is1, N, M):
    for i in range(N):
        for j in range(M):
            if (is1):
                grid[i][j] = '0'
                is1 = False
 
            else:
                grid[i][j] = '1'
                is1 = True
 
        if (M % 2 == 0):
            is1 = True if is1 == False else False
 
# Function to test if any one of them
# matches with the given 2-D array
def testGrid(testGrid, Grid, N, M):
    for i in range(N):
        for j in range(M):
            if (Grid[i][j] != '*'):
                if (Grid[i][j] != testGrid[i][j]):
                    return False
 
    return True
 
# Function to print the grid, if possible
def printGrid(grid, N, M):
    for i in range(N):
        for j in range(M):
            print(grid[i][j],end = " ")
        print("\n",end = "")
 
# Function to check if the grid
# can be made alternating or not
def findPossibleGrid(N, M, grid):
    # Grids to store the possible grids
    gridTest1 = [['' for i in range(1001)] for j in range(N)]
    gridTest2 = [['' for i in range(1001)] for j in range(N)]
 
    createGrid(gridTest1, True, N, M)
 
    createGrid(gridTest2, False, N, M)
 
    if(testGrid(gridTest1, grid, N, M)):
        print("Yes")
        printGrid(gridTest1, N, M)
 
    elif(testGrid(gridTest2, grid, N, M)):
        print("Yes")
        printGrid(gridTest2, N, M)
    else:
        print("No")
 
# Driver Code
if __name__ == '__main__':
    N = 4
    M = 4
    grid  = [['*', '*', '1', '0'],
             ['*', '*', '*', '*'],
             ['*', '*', '*', '*'],
             ['*', '*', '0', '1']]
 
    findPossibleGrid(N, M, grid)
     
    # This code is contributed by ipg2016107.


C#




// C# program for the above approach
using System;
 
class GFG{
     
// Function to create the possible grids
public static void createGrid(char[,] grid,
                              bool is1,
                              int N, int M)
{
    for(int i = 0; i < N; i++)
    {
        for(int j = 0; j < M; j++)
        {
            if (is1)
            {
                grid[i, j] = '0';
                is1 = false;
            }
            else
            {
                grid[i, j] = '1';
                is1 = true;
            }
        }
        if (M % 2 == 0)
            is1 = !is1;
    }
}
 
// Function to test if any one of them
// matches with the given 2-D array
public static bool testGrid(char[,] testGrid,
                            char[,] Grid, int N,
                            int M)
{
    for(int i = 0; i < N; i++)
    {
        for(int j = 0; j < M; j++)
        {
            if (Grid[i, j] != '*')
            {
                if (Grid[i, j] != testGrid[i, j])
                {
                    return false;
                }
            }
        }
    }
    return true;
}
 
// Function to print the grid, if possible
public static void printGrid(char[,] grid, int N,
                             int M)
{
    for(int i = 0; i < N; i++)
    {
        for(int j = 0; j < M; j++)
        {
            Console.Write(grid[i, j] + " ");
        }
        Console.WriteLine();
    }
}
 
// Function to check if the grid
// can be made alternating or not
public static void findPossibleGrid(int N, int M,
                                    char[,] grid)
{
     
    // Grids to store the possible grids
    char[,] gridTest1 = new char[N, 1001];
    char[,] gridTest2 = new char[N, 1001];
 
    createGrid(gridTest1, true, N, M);
    createGrid(gridTest2, false, N, M);
 
    if (testGrid(gridTest1, grid, N, M))
    {
        Console.WriteLine("Yes");
        printGrid(gridTest1, N, M);
    }
    else if (testGrid(gridTest2, grid, N, M))
    {
        Console.WriteLine("Yes");
        printGrid(gridTest2, N, M);
    }
    else
    {
        Console.WriteLine("No");
    }
}
 
// Driver code
public static void Main()
{
    int N = 4, M = 4;
    char[,] grid = { { '*', '*', '1', '0' },
                     { '*', '*', '*', '*' },
                     { '*', '*', '*', '*' },
                     { '*', '*', '0', '1' } };
     
    findPossibleGrid(N, M, grid);
}
}
 
// This code is contributed by sanjoy_62


Javascript




<script>
 
// JavaScript program for the above approach
 
// Function to create the possible grids
function createGrid(grid, is1, N, M) {
  for (let i = 0; i < N; i++) {
    for (let j = 0; j < M; j++) {
      if (is1) {
        grid[i][j] = "0";
        is1 = false;
      } else {
        grid[i][j] = "1";
        is1 = true;
      }
    }
    if (M % 2 == 0) is1 = !is1;
  }
}
 
// Function to test if any one of them
// matches with the given 2-D array
function testGrid(testGrid, Grid, N, M) {
  for (let i = 0; i < N; i++) {
    for (let j = 0; j < M; j++) {
      if (Grid[i][j] != "*") {
        if (Grid[i][j] != testGrid[i][j]) {
          return false;
        }
      }
    }
  }
  return true;
}
 
// Function to print the grid, if possible
function printGrid(grid, N, M) {
  for (let i = 0; i < N; i++) {
    for (let j = 0; j < M; j++) {
      document.write(grid[i][j] + " ");
    }
    document.write("<br>");
  }
}
 
// Function to check if the grid
// can be made alternating or not
function findPossibleGrid(N, M, grid) {
  // Grids to store the possible grids
  let gridTest1 = new Array(N).fill(0).map(() => new Array(1001));
  let gridTest2 = new Array(N).fill(0).map(() => new Array(1001));
 
  createGrid(gridTest1, true, N, M);
 
  createGrid(gridTest2, false, N, M);
 
  if (testGrid(gridTest1, grid, N, M)) {
    document.write("Yes<br>");
    printGrid(gridTest1, N, M);
  } else if (testGrid(gridTest2, grid, N, M)) {
    document.write("Yes<br>");
    printGrid(gridTest2, N, M);
  } else {
    document.write("No<br>");
  }
}
 
// Driver Code
 
let N = 4,
  M = 4;
let grid = [
  ["*", "*", "1", "0"],
  ["*", "*", "*", "*"],
  ["*", "*", "*", "*"],
  ["*", "*", "0", "1"],
];
 
findPossibleGrid(N, M, grid);
 
</script>


Output

Yes
1 0 1 0 
0 1 0 1 
1 0 1 0 
0 1 0 1 

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

Efficient Approach: The idea is to use two variables instead of creating the 2-D arrays to maintain the possible alternating arrays. Follow the steps below to solve the problem:

  • Define a function posCheck(char grid[][1001], int N, int M, char check) and perform the following tasks:
    • Iterate over the range [0, N] using the variable i and performing the following tasks:
      • Iterate over the range [0, M] using the variable j and performing the following tasks:
        • If grid[i][j] is equal to β€˜*’, then continue.
        • Else, if (i+j)%2 is equal to 1 and grid[i][j] is not equal to check, then return false.
        • Else, if (i+j)%2 is equal to 0 and grid[i][j] is equal to check, then return false.
    • After performing the above steps, return the value of true as the answer.
  • Define a function posCheck(char grid[][1001], int N, int M, char odd, char even) and perform the following tasks:
    • Iterate over the range [0, N] using the variable i and performing the following tasks:
      • Iterate over the range [0, M] using the variable j and performing the following tasks:
        • If (i+j)%2 is equal to 1, then set the value of grid[i][j] to odd else even.
  • Initialize the bool variable flag as true.
  • Initialize the variables k and o as -1 to store the value of the first cell which doesn’t have the character β€˜*’.
  • Iterate over the range [0, N] using the variable i and performing the following tasks:
    • Iterate over the range [0, M] using the variable j and performing the following tasks:
      • If Grid[i][j] is not equal to β€˜*’, then set the value of k as i and o as j and break.
    • If k is not equal to -1, then break.
  • If k is not equal to -1, then call the function PosCheck(grid, n, m, β€˜1’) and store the value returned by the function in the variable flag and if flag is true, then call the function fill(grid, n, m, β€˜1’, β€˜0’) to fill the grid in one of the possible ways.
  • If flag is false, then call the function PosCheck(grid, n, m, β€˜0’) and store the value returned by the function in the variable flag and if flag is true, then call the function fill(grid, n, m, β€˜0’, β€˜1’) to fill the grid in one of the possible ways.
  • If k is equal to -1, then, initialize the char variable h as β€˜0’.
  • Iterate over the range [0, M] using the variable i and performing the following tasks:
    • Set the value of grid[0][i] as h and if h is β€˜0β€˜, then set it to β€˜1β€˜, otherwise β€˜0’.
  • Iterate over the range [0, N] using the variable i and performing the following tasks:
    • Iterate over the range [0, M] using the variable j and performing the following tasks:
      • If i-1 is less than 0, then continue.
      • If grid[i-1][j] is β€˜1’, then set it to β€˜0’, else β€˜1’.
  • Set the value of flag as true as the grid is made alternating.
  • If flag is false, then print β€œNO”.
  • Else, print β€œYES” and print the elements of the grid[][].

Below is the implementation of the above approach. 

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to check for the grid in
// one of the alternating ways
bool PosCheck(char a[][1001], int n,
              int m, char check)
{
 
    // Iterate over the range
    for (int i = 0; i < n; i++) {
 
        // Iterate over the range
        for (int j = 0; j < m; j++) {
 
            if (a[i][j] == '*') {
                continue;
            }
            else {
 
                // (i+j)%2==1 cells should be with
                // the character check and the rest
                // should be with the other character
                if (((i + j) & 1) && a[i][j] != check) {
                    return false;
                }
                if (!((i + j) & 1) && a[i][j] == check) {
                    return false;
                }
            }
        }
    }
    return true;
}
 
// Function to fill the grid in a possible way
void fill(char a[][1001], int n, int m,
          char odd, char even)
{
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            if ((i + j) & 1) {
                a[i][j] = odd;
            }
            else {
                a[i][j] = even;
            }
        }
    }
}
 
// Function to find if the grid can be made alternating
void findPossibleGrid(int n, int m, char a[][1001])
{
    bool flag = true;
    int k = -1, o = -1;
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
 
            if (a[i][j] != '*') {
 
                // If grid contains atleast
                // one 1 or 0
                k = i;
                o = j;
                break;
            }
        }
        if (k != -1) {
            break;
        }
    }
    if (k != -1) {
        flag = PosCheck(a, n, m, '1');
        if (flag) {
            fill(a, n, m, '1', '0');
        }
        else {
            flag = PosCheck(a, n, m, '0');
            if (flag) {
                fill(a, n, m, '0', '1');
            }
        }
    }
    else {
        // Fill the grid in any possible way
        char h = '1';
        for (int i = 0; i < m; i++) {
            a[0][i] = h;
            if (h == '1') {
                h = '0';
            }
            else {
                h = '1';
            }
        }
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (i - 1 < 0) {
                    continue;
                }
                if (a[i - 1][j] == '1') {
                    a[i][j] = '0';
                }
                else {
                    a[i][j] = '1';
                }
            }
        }
        flag = true;
    }
 
    if (!flag) {
        cout << "NO\n";
    }
    else {
        cout << "YES\n";
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                cout << a[i][j];
            }
            cout << endl;
        }
    }
}
 
// Driver Code
int main()
{
    int n = 4, m = 4;
    char grid[][1001] = { { '*', '*', '1', '0' },
                          { '*', '*', '*', '*' },
                          { '*', '*', '*', '*' },
                          { '*', '*', '0', '1' } };
 
    findPossibleGrid(n, m, grid);
 
    return 0;
}


Java




/*package whatever //do not write package name here */
 
import java.io.*;
 
class GFG {
    public static boolean PosCheck(char[][] a, int n, int m,
                                   char check)
    {
 
        // Iterate over the range
        for (int i = 0; i < n; i++) {
 
            // Iterate over the range
            for (int j = 0; j < m; j++) {
 
                if (a[i][j] == '*') {
                    continue;
                }
                else {
 
                    // (i+j)%2==1 cells should be with
                    // the character check and the rest
                    // should be with the other character
                    if ((((i + j) & 1) == 1)
                        && a[i][j] != check) {
                        return false;
                    }
                    if (!(((i + j) & 1) == 1)
                        && a[i][j] == check) {
                        return false;
                    }
                }
            }
        }
        return true;
    }
 
    // Function to fill the grid in a possible way
    public static void fill(char[][] a, int n, int m,
                            char odd, char even)
    {
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (((i + j) & 1) == 1) {
                    a[i][j] = odd;
                }
                else {
                    a[i][j] = even;
                }
            }
        }
    }
 
    // Function to find if the grid can be made alternating
    public static void findPossibleGrid(int n, int m,
                                        char[][] a)
    {
        boolean flag = true;
        int k = -1, o = -1;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
 
                if (a[i][j] != '*') {
 
                    // If grid contains atleast
                    // one 1 or 0
                    k = i;
                    o = j;
                    break;
                }
            }
            if (k != -1) {
                break;
            }
        }
        if (k != -1) {
            flag = PosCheck(a, n, m, '1');
            if (flag) {
                fill(a, n, m, '1', '0');
            }
            else {
                flag = PosCheck(a, n, m, '0');
                if (flag) {
                    fill(a, n, m, '0', '1');
                }
            }
        }
        else {
            // Fill the grid in any possible way
            char h = '1';
            for (int i = 0; i < m; i++) {
                a[0][i] = h;
                if (h == '1') {
                    h = '0';
                }
                else {
                    h = '1';
                }
            }
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < m; j++) {
                    if (i - 1 < 0) {
                        continue;
                    }
                    if (a[i - 1][j] == '1') {
                        a[i][j] = '0';
                    }
                    else {
                        a[i][j] = '1';
                    }
                }
            }
            flag = true;
        }
 
        if (!flag) {
            System.out.println("No");
        }
        else {
            System.out.println("Yes");
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < m; j++) {
                    System.out.print(a[i][j]);
                }
                System.out.println();
            }
        }
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int n = 4, m = 4;
        char[][] grid = { { '*', '*', '1', '0' },
                          { '*', '*', '*', '*' },
                          { '*', '*', '*', '*' },
                          { '*', '*', '0', '1' } };
 
        findPossibleGrid(n, m, grid);
    }
}
 
// This code is contributed by maddler.


Python3




# Python program for the above approach
 
# Function to check for the grid in
# one of the alternating ways
def PosCheck(a, n, m, check):
 
  # Iterate over the range
  for i in range(n):
   
    # Iterate over the range
    for j in range(m):
 
        if (a[i][j] == "*"):
            continue
        else:
       
            # (i+j)%2==1 cells should be with
            # the character check and the rest
            # should be with the other character
            if (((i + j) & 1) and a[i][j] != check):
                return False
            if (((i + j) & 1) == 0 and a[i][j] == check):
                return False
    return True
 
# Function to fill the grid in a possible way
def fill(a, n, m, odd, even):
     
    for i in range(n):
        for j in range(m):
            if ((i + j) & 1):
                a[i][j] = odd
            else:
                a[i][j] = even
 
# Function to find if the grid can be made alternating
def findPossibleGrid(n, m, a):
    flag,k,O = True,-1,-1
    for i in range(n):
        for j in range(m):
            if (a[i][j] != "*"):
       
                # If grid contains atleast
                # one 1 or 0
                k = i
                O = j
                break
 
        if (k != -1):
            break
    if (k != -1):
        flag = PosCheck(a, n, m, "1")
        if (flag):
            fill(a, n, m, "1", "0")
        else:
            flag = PosCheck(a, n, m, "0")
            if (flag):
                fill(a, n, m, "0", "1")
    else:
   
        # Fill the grid in any possible way
        h = "1"
        for i in range(m):
            a[0][i] = h
            if (h == "1"):
                h = "0"
            else:
                h = "1"
        for i in range(n):
            for j in range(m):
                if (i - 1 < 0):
                    continue
                if (a[i - 1][j] == "1"):
                    a[i][j] = "0"
                else:
                    a[i][j] = "1"
        flag = True
 
    if (flag == 0):
        print("NO")
    else:
        print("YES")
         
        for i in range(n):
            for j in range(m):
                print(a[i][j],end="")
            print()
 
# Driver Code
n,m = 4,4
grid = [
  ["*", "*", "1", "0"],
  ["*", "*", "*", "*"],
  ["*", "*", "*", "*"],
  ["*", "*", "0", "1"],
]
 
findPossibleGrid(n, m, grid)
 
# This code is contributed by shinjanpatra


C#




// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
     
    public static bool PosCheck(char[,] a, int n, int m,
                                   char check)
    {
 
        // Iterate over the range
        for (int i = 0; i < n; i++) {
 
            // Iterate over the range
            for (int j = 0; j < m; j++) {
 
                if (a[i, j] == '*') {
                    continue;
                }
                else {
 
                    // (i+j)%2==1 cells should be with
                    // the character check and the rest
                    // should be with the other character
                    if ((((i + j) & 1) == 1)
                        && a[i, j] != check) {
                        return false;
                    }
                    if (!(((i + j) & 1) == 1)
                        && a[i, j] == check) {
                        return false;
                    }
                }
            }
        }
        return true;
    }
 
    // Function to fill the grid in a possible way
    public static void fill(char[,] a, int n, int m,
                            char odd, char even)
    {
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (((i + j) & 1) == 1) {
                    a[i, j] = odd;
                }
                else {
                    a[i, j] = even;
                }
            }
        }
    }
 
    // Function to find if the grid can be made alternating
    public static void findPossibleGrid(int n, int m,
                                        char[,] a)
    {
        bool flag = true;
        int k = -1, o = -1;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
 
                if (a[i, j] != '*') {
 
                    // If grid contains atleast
                    // one 1 or 0
                    k = i;
                    o = j;
                    break;
                }
            }
            if (k != -1) {
                break;
            }
        }
        if (k != -1) {
            flag = PosCheck(a, n, m, '1');
            if (flag) {
                fill(a, n, m, '1', '0');
            }
            else {
                flag = PosCheck(a, n, m, '0');
                if (flag) {
                    fill(a, n, m, '0', '1');
                }
            }
        }
        else {
            // Fill the grid in any possible way
            char h = '1';
            for (int i = 0; i < m; i++) {
                a[0, i] = h;
                if (h == '1') {
                    h = '0';
                }
                else {
                    h = '1';
                }
            }
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < m; j++) {
                    if (i - 1 < 0) {
                        continue;
                    }
                    if (a[i - 1, j] == '1') {
                        a[i, j] = '0';
                    }
                    else {
                        a[i, j] = '1';
                    }
                }
            }
            flag = true;
        }
 
        if (!flag) {
            Console.WriteLine("No");
        }
        else {
            Console.WriteLine("Yes");
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < m; j++) {
                    Console.Write(a[i, j]);
                }
                Console.WriteLine();
            }
        }
    }
 
// Driver Code
public static void Main()
{
        int n = 4, m = 4;
        char[,] grid = { { '*', '*', '1', '0' },
                          { '*', '*', '*', '*' },
                          { '*', '*', '*', '*' },
                          { '*', '*', '0', '1' } };
 
        findPossibleGrid(n, m, grid);
}
}
 
// This code is contributed by splevel62.


Javascript




<script>
// Javascript program for the above approach
 
// Function to check for the grid in
// one of the alternating ways
function PosCheck(a, n, m, check)
{
 
  // Iterate over the range
  for (let i = 0; i < n; i++)
  {
   
    // Iterate over the range
    for (let j = 0; j < m; j++)
    {
      if (a[i][j] == "*")
      {
        continue;
      }
      else
      {
       
        // (i+j)%2==1 cells should be with
        // the character check and the rest
        // should be with the other character
        if ((i + j) & 1 && a[i][j] != check) {
          return false;
        }
        if (!((i + j) & 1) && a[i][j] == check) {
          return false;
        }
      }
    }
  }
  return true;
}
 
// Function to fill the grid in a possible way
function fill(a, n, m, odd, even) {
  for (let i = 0; i < n; i++) {
    for (let j = 0; j < m; j++) {
      if ((i + j) & 1) {
        a[i][j] = odd;
      } else {
        a[i][j] = even;
      }
    }
  }
}
 
// Function to find if the grid can be made alternating
function findPossibleGrid(n, m, a) {
  let flag = true;
  let k = -1,
    o = -1;
  for (let i = 0; i < n; i++) {
    for (let j = 0; j < m; j++) {
      if (a[i][j] != "*")
      {
       
        // If grid contains atleast
        // one 1 or 0
        k = i;
        o = j;
        break;
      }
    }
    if (k != -1) {
      break;
    }
  }
  if (k != -1) {
    flag = PosCheck(a, n, m, "1");
    if (flag) {
      fill(a, n, m, "1", "0");
    } else {
      flag = PosCheck(a, n, m, "0");
      if (flag) {
        fill(a, n, m, "0", "1");
      }
    }
  }
  else
  {
   
    // Fill the grid in any possible way
    let h = "1";
    for (let i = 0; i < m; i++) {
      a[0][i] = h;
      if (h == "1") {
        h = "0";
      } else {
        h = "1";
      }
    }
    for (let i = 0; i < n; i++) {
      for (let j = 0; j < m; j++) {
        if (i - 1 < 0) {
          continue;
        }
        if (a[i - 1][j] == "1") {
          a[i][j] = "0";
        } else {
          a[i][j] = "1";
        }
      }
    }
    flag = true;
  }
 
  if (!flag) {
    document.write("NO<br>");
  } else {
    document.write("YES<br>");
    for (let i = 0; i < n; i++)
    {
      for (let j = 0; j < m; j++)
      {
        document.write(a[i][j]);
      }
      document.write("<br>");
    }
  }
}
 
// Driver Code
 
let n = 4,
  m = 4;
let grid = [
  ["*", "*", "1", "0"],
  ["*", "*", "*", "*"],
  ["*", "*", "*", "*"],
  ["*", "*", "0", "1"],
];
 
findPossibleGrid(n, m, grid);
 
// This code is contributed by saurabh_jaiswal.
</script>


Output

YES
1010
0101
1010
0101

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