Check if the given chessboard is valid or not

Last Updated : 27 Mar, 2025

Given an n × n chessboard. The task is to check if the given chessboard is valid or not. A chess board is considered valid if every 2 adjacent cells are painted differently. Two cells are considered adjacent if they share a boundary. 

Examples: 

Input : n = 2, C = [ [ 1, 0 ], [ 0, 1 ] ]
Output : Yes
Explanation: All adjacent cells are painted differently hence a valid chessboard.

Input : n = 2, C = [ [ 1, 0 ], [ 0, 0 ]]
Output : No
Explanation: All adjacent cells are not painted differently hence not a valid chessboard.

The first chessboard is valid, whereas the second is invalid.

[Naive Approach] - Checking all adjacent Cells

This idea for this approach is to verify that each cell on the grid has a different color than its directly adjacent neighbors. For a given cell (i, j), its adjacent cells are the ones directly above, below, left, and right, i.e., (i + 1, j), (i - 1, j), (i, j + 1), and (i, j - 1)

C++
#include <bits/stdc++.h>
using namespace std;

// Check if the given chess board is valid or not.
bool isValid(vector<vector<int>>& c, int n)
{
    int X[] = { 0, -1, 0, 1 };
    int Y[] = { 1, 0, -1, 0 };
    bool isValid = true;

    // Traversing each cell of the chess board.
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {

            // for each adjacent cells
            for (int k = 0; k < 4; k++) {
                int newX = i + X[k];
                int newY = j + Y[k];

                // checking if they have different color
                if (newX < n && newY < n && newX >= 0 && 
                    newY >= 0 && c[newX][newY] == c[i][j]) {
                    isValid = false;
                }
            }
        }
    }
    return isValid;
}

int main()
{
    int n = 2;
    vector<vector<int>> c = { { 1, 0 },
                                { 0, 1 } };

    (isValid(c, n)) ? (cout << "Yes") : (cout << "No");
    return 0;
}
C
#include <stdio.h>
#include <stdbool.h>

#define MAX 100

// Check if the given chess board is valid or not.
bool isValid(int c[MAX][MAX], int n)
{
    int X[] = { 0, -1, 0, 1 };
    int Y[] = { 1, 0, -1, 0 };
    bool isValid = true;

    // Traversing each cell of the chess board.
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {

            // for each adjacent cells
            for (int k = 0; k < 4; k++) {
                int newX = i + X[k];
                int newY = j + Y[k];

                // checking if they have different color
                if (newX < n && newY < n && newX >= 0 && 
                    newY >= 0 && c[newX][newY] == c[i][j]) {
                    isValid = false;
                }
            }
        }
    }
    return isValid;
}

int main()
{
    int n = 2;
    int c[MAX][MAX] = { { 1, 0 },
                         { 0, 1 } };

    (isValid(c, n)) ? (printf("Yes")) : (printf("No"));
    return 0;
}
Java
class GfG 
{
static int MAX = 2;

static boolean isValid(int c[][], int n)
{
    int X[] = { 0, -1, 0, 1 };
    int Y[] = { 1, 0, -1, 0 };
    boolean isValid = true;

    // Traversing each cell 
    // of the chess board.
    for (int i = 0; i < n; i++) 
    {
        for (int j = 0; j < n; j++)
        {

            // for each adjacent cells
            for (int k = 0; k < 4; k++) 
            {
                int newX = i + X[k];
                int newY = j + Y[k];

                // checking if they have
                // different color
                if (newX < n && newY < n && 
                    newX >= 0 && newY >= 0 &&
                    c[newX][newY] == c[i][j])
                {
                    isValid = false;
                }
            }
        }
    }
    return isValid;
}


public static void main(String[] args) 
{
    int n = 2;
    int[][] c = {{ 1, 0 },
                 { 0, 1 }};

    if (isValid(c, n)) 
        System.out.println("Yes");
    else
        System.out.println("No");
}
} 
Python
MAX = 2

# Check if the given chess
# board is valid or not.
def isValid(c, n) :

    X = [ 0, -1, 0, 1]
    Y = [ 1, 0, -1, 0]
    isValid = True

    # Traversing each cell 
    # of the chess board. 
    for i in range(n) :
        for j in range(n) :
            
            # for each adjacent cells
            for k in range(n) :
                newX = i + X[k]
                newY = j + Y[k]

                # checking if they have
                # different color 
                if (newX < n and newY < n and 
                    newX >= 0 and newY >= 0 and 
                    c[newX][newY] == c[i][j]) :
                    isValid = false

    return isValid

if __name__ == "__main__" :
    n = 2
    c = [ [1, 0],
          [0, 1] ]

    if isValid(c, n) :
        print("Yes")

    else :
        print("No")
C#
using System;

class GFG 
{

static bool isValid(int[,] c, int n)
{
    int[] X = { 0, -1, 0, 1 };
    int[] Y = { 1, 0, -1, 0 };
    bool isValid = true;

    // Traversing each cell 
    // of the chess board.
    for (int i = 0; i < n; i++) 
    {
        for (int j = 0; j < n; j++) 
        {

            // for each adjacent cells
            for (int k = 0; k < 4; k++) 
            {
                int newX = i + X[k];
                int newY = j + Y[k];

                // checking if they have different color
                if (newX < n && newY < n && 
                    newX >= 0 && newY >= 0 && 
                    c[newX, newY] == c[i, j]) 
                {
                    isValid = false;
                }
            }
        }
    }
    return isValid;
}

public static void Main() 
{
    int n = 2;
    int[,] c = {{ 1, 0 },
                { 0, 1 }};

    if (isValid(c, n)) 
        Console.Write("Yes");
    else
        Console.Write("No");
}
} 
JavaScript
function isValid(c, n)
{
    var X = [ 0, -1, 0, 1 ];
    var Y = [ 1, 0, -1, 0 ];
    var isValid = true;

    // Traversing each cell of the chess board.
    for (var i = 0; i < n; i++) {
        for (var j = 0; j < n; j++) {

            // for each adjacent cells
            for (var k = 0; k < 4; k++) {
                var newX = i + X[k];
                var newY = j + Y[k];

                // checking if they have
                // different color
                if (newX < n && newY < n && 
                newX >= 0 && 
                newY >= 0 && 
                c[newX][newY] == c[i][j]) {
                    isValid = false;
                }
            }
        }
    }
    return isValid;
}


var n = 2;
var c = [ [ 1, 0 ],
                [ 0, 1 ] ];
(isValid(c, n)) ? (console.log( "Yes")) : 
(console.log( "No"));

Output
Yes

Time complexity: O(n^2) for given an n*n chessboard
Auxiliary space: O(1)

[Expected Approach] - Checking the Color of Cells With Even and Odd Sum

A simpler approach would be to check if the cells with even sums (of row and column indexes) are of the same color and cells with odd sums are of same color. The idea for this approach is based on the property of a chessboard pattern where the color of each cell alternates based on the sum of its row and column indices. If the sum of the indices i + j is even, the cell is typically black; if it's odd, the cell is white.

C++
#include <iostream>
#include <vector>
using namespace std;

bool checkBoard(vector<vector<int>> &board)
{
    int base = board[0][0];
    bool flag = true;
 
    for(int i = 0; i < board.size(); i++)
    {
        for( int j = 0; j < board[i].size(); j++)
        {
            if(( i + j ) % 2 == 0)
            {
                if( board[i][j] != base )
                {
                    return false;
                }
            }
            else
            {
                if (board[i][j] == base)
                {
                    return false;
                }
            }
        }
    }
    return true;
}

int main()
{
    vector<vector<int>> board1={{0, 1}, 
                                {1, 0}};
                    
    vector<vector<int>> board2={{1, 0, 1},
                                {0, 1, 0},
                                {1, 0, 1}};
                    
    vector<vector<int>> board3={{1, 0, 1},
                                {0, 1, 0},
                                {1, 1, 1}};
 
    if(checkBoard(board1))
    cout << "true\n";
    else
    cout << "false\n";
    
    if(checkBoard(board2))
    cout << "true\n";
    else
    cout << "false\n";
    
    if(checkBoard(board3))
    cout << "true\n";
    else
    cout << "false\n";
    
    return 0;
}
//This code is contributed by aditya942003patil to the following languages: c.
C
#include <stdio.h>
#include <stdbool.h>

#define MAX 100

bool checkBoard(int board[MAX][MAX], int rows, int cols)
{
    int base = board[0][0];
    bool flag = true;
 
    for(int i = 0; i < rows; i++)
    {
        for( int j = 0; j < cols; j++)
        {
            if(( i + j ) % 2 == 0)
            {
                if( board[i][j] != base )
                {
                    return false;
                }
            }
            else
            {
                if (board[i][j] == base)
                {
                    return false;
                }
            }
        }
    }
    return true;
}

int main()
{
    int board1[2][2] = {{0, 1}, 
                        {1, 0}};
    int board2[3][3] = {{1, 0, 1},
                        {0, 1, 0},
                        {1, 0, 1}};
    int board3[3][3] = {{1, 0, 1},
                        {0, 1, 0},
                        {1, 1, 1}};
 
    if(checkBoard(board1, 2, 2))
        printf("true\n");
    else
        printf("false\n");
    
    if(checkBoard(board2, 3, 3))
        printf("true\n");
    else
        printf("false\n");
    
    if(checkBoard(board3, 3, 3))
        printf("true\n");
    else
        printf("false\n");
    
    return 0;
}
Java
import java.util.*;

public class Main {
    public static boolean checkBoard(int[][] board) {
        int base = board[0][0];
        boolean flag = true;
 
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[i].length; j++) {
                if ((i + j) % 2 == 0) {
                    if (board[i][j] != base) {
                        return false;
                    }
                } else {
                    if (board[i][j] == base) {
                        return false;
                    }
                }
            }
        }
        return true;
    }

    public static void main(String[] args) {
        int[][] board1 = {{0, 1}, {1, 0}};
        int[][] board2 = {{1, 0, 1}, {0, 1, 0}, {1, 0, 1}};
        int[][] board3 = {{1, 0, 1}, {0, 1, 0}, {1, 1, 1}};
 
        System.out.println(checkBoard(board1) ? "true" : "false");
        System.out.println(checkBoard(board2) ? "true" : "false");
        System.out.println(checkBoard(board3) ? "true" : "false");
    }
}
//This code is contributed by aditya942003patil to the following languages: c.
Python
def check_board(board):
    base = board[0][0]
    
    for i in range(len(board)):
        for j in range(len(board[i])):
            if (i + j) % 2 == 0:
                if board[i][j] != base:
                    return False
            else:
                if board[i][j] == base:
                    return False
    return True

board1 = [[0, 1], [1, 0]]
board2 = [[1, 0, 1], [0, 1, 0], [1, 0, 1]]
board3 = [[1, 0, 1], [0, 1, 0], [1, 1, 1]]

print("true" if check_board(board1) else "false")
print("true" if check_board(board2) else "false")
print("true" if check_board(board3) else "false")
#This code is contributed by aditya942003patil to the following languages: c.
C#
using System;
using System.Collections.Generic;

class Program {
    public static bool CheckBoard(int[,] board) {
        int baseVal = board[0, 0];
        
        for (int i = 0; i < board.GetLength(0); i++) {
            for (int j = 0; j < board.GetLength(1); j++) {
                if ((i + j) % 2 == 0) {
                    if (board[i, j] != baseVal) {
                        return false;
                    }
                } else {
                    if (board[i, j] == baseVal) {
                        return false;
                    }
                }
            }
        }
        return true;
    }

    static void Main() {
        int[,] board1 = {{0, 1}, {1, 0}};
        int[,] board2 = {{1, 0, 1}, {0, 1, 0}, {1, 0, 1}};
        int[,] board3 = {{1, 0, 1}, {0, 1, 0}, {1, 1, 1}};

        Console.WriteLine(CheckBoard(board1) ? "true" : "false");
        Console.WriteLine(CheckBoard(board2) ? "true" : "false");
        Console.WriteLine(CheckBoard(board3) ? "true" : "false");
    }
}
//This code is contributed by aditya942003patil to the following languages: c.
JavaScript
function checkBoard(board)
{
    let base = board[0][0];
let flag = true;

for(let i = 0; i < board.length; i++)
{
  for( let j = 0; j < board[i].length; j++)
  {
    if(( i + j ) % 2 == 0)
    {
      if( board[i][j] != base )
      {
        return false;
      }
    }
    else
    {
      if (board[i][j] == base)
      {
        return false;
      }
    }
  }
}
return true;
}

let board1 = [[0, 1], [1, 0]];
let board2 = [[1, 0, 1], [0, 1, 0], [1, 0, 1]];
let board3 = [[1, 0, 1], [0, 1, 0], [1, 1, 1]];

console.log(checkBoard(board1))
console.log(checkBoard(board2))
console.log(checkBoard(board3))

Output
true
true
false

Time complexity: O(n^2) for given an n*n chessboard
Auxiliary space: O(1)

Comment