 Open in App
Not now

# Python program to print checkerboard pattern of nxn using numpy

• Difficulty Level : Medium
• Last Updated : 14 Mar, 2023

Given n, print the  checkerboard pattern for a n x n matrix  Checkerboard Pattern for n = 8: It consists of n * n squares of alternating 0 for white and 1 for black.

## Recommended: Please try your approach on {IDE} first, before moving on to the solution.

We can do the same using nested for loops and some if conditions, but using Python’s numpy library, we can import a 2-D matrix and get the checkerboard pattern using slicing. W2’ll be using following python function to print pattern :

`x = np.zeros((n, n), dtype=int)`

Using this function, we initialize a 2-D matrix with 0’s at all index using numpy

• x[1::2, ::2] = 1 : Slice from 1st index row till 1+2+2… and fill all columns with 1 starting from 0th to 0+2+2… and so on.
• x[::2, 1::2] = 1 : Slice from 0th row till 0+2+2… and fill all columns with 1 starting from 1 to 1+2+2+…..

Function of np.zeros((n, n), dtype=int) : Often, the elements of an array are originally unknown, but its size is known. Hence, NumPy offers several functions to create arrays with initial placeholder content. These minimize the necessity of growing arrays, an expensive operation. Using the dtype parameter initializes all the values with int data-type. For example: np.zeros, np.ones etc.

## Python3

 `import` `numpy as np` `# function to print Checkerboard pattern``def` `printcheckerboard(n):``    ``print``(``"Checkerboard pattern:"``)` `    ``# create a n * n matrix``    ``x ``=` `np.zeros((n, n), dtype``=``int``)` `    ``# fill with 1 the alternate cells in rows and columns``    ``x[``1``::``2``, ::``2``] ``=` `1``    ``x[::``2``, ``1``::``2``] ``=` `1` `    ``# print the pattern``    ``for` `i ``in` `range``(n):``        ``for` `j ``in` `range``(n):``            ``print``(x[i][j], end``=``" "``)``        ``print``()` `# driver code``n ``=` `8``printcheckerboard(n)`

## Java

 `import` `java.util.Arrays;` `public` `class` `CheckerboardPattern {` `    ``public` `static` `void` `printCheckerboard(``int` `n) {``        ``System.out.println(``"Checkerboard pattern:"``);``        ` `        ``// create a n * n matrix filled with zeros``        ``int``[][] x = ``new` `int``[n][n];``        ` `        ``// fill with 1 the alternate cells in rows and columns``        ``for` `(``int` `i = ``1``; i < n; i += ``2``) {``            ``for` `(``int` `j = ``0``; j < n; j += ``2``) {``                ``x[i][j] = ``1``;``            ``}``        ``}``        ` `        ``for` `(``int` `i = ``0``; i < n; i += ``2``) {``            ``for` `(``int` `j = ``1``; j < n; j += ``2``) {``                ``x[i][j] = ``1``;``            ``}``        ``}``        ` `        ``// print the pattern``        ``for` `(``int``[] row : x) {``            ``System.out.println(Arrays.toString(row)``                ``.replace(``","``, ``""``)``                ``.replace(``"["``, ``""``)``                ``.replace(``"]"``, ``""``));``        ``}``    ``}` `    ``public` `static` `void` `main(String[] args) {``        ``int` `n = ``8``;``        ``printCheckerboard(n);``    ``}``}`

Output:

```Checkerboard pattern:
0 1 0 1 0 1 0 1
1 0 1 0 1 0 1 0
0 1 0 1 0 1 0 1
1 0 1 0 1 0 1 0
0 1 0 1 0 1 0 1
1 0 1 0 1 0 1 0
0 1 0 1 0 1 0 1
1 0 1 0 1 0 1 0 ```

Time complexity: The time complexity of this code is O(n^2) because it uses two nested loops to fill and print the matrix. The loop iterations depend on the input value of ‘n’.

Space complexity: The space complexity of this code is also O(n^2) because it creates a matrix of size n x n to store the checkerboard pattern. The space used by other variables and the function call stack is negligible compared to the size of the matrix.

Improved Source Code Based on Assumption that Checkerboard is always an even nXn i.e., n is even

## Python3

 `# Python program to print nXn Assuming that n``# is always even as a checkerboard was` `import` `numpy as np``def` `printcheckboard(n):``    ``final ``=` `[]``    ``for` `i ``in` `range``(n):``        ``final.append(``list``(np.tile([``0``,``1``],``int``(n``/``2``))) ``if` `i``%``2``=``=``0` `else` `list``(np.tile([``1``,``0``],``int``(n``/``2``))))``    ``print``(np.array(final))`  `# driver code``n ``=` `8``printcheckboard(n)`

Output:

```Checkerboard pattern:
[[0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0]
[0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0]
[0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0]
[0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0]]```

My Personal Notes arrow_drop_up