# Initialize game board in matrix – Code

Initialize game board in matrix is to populate one digit number into a NxN matrix. The digit can be generated randomly. However, no 3 adjacent cells shall be the same, horizontal, vertical, diagonal and L shape. If you find invalid digit, replace with a different one in that cell.

What is matrix? Matrix is 2D array, which reflects the game game in real world perfectly. The popular game board questions such as tic tac toe, sudoku, or chess board, all use matrix.

The trick in this question is the cells at the edge. Their adjacent cells are not defined in matrix. The workaround is to define another matrix that has one more cell at both sides. It not only covers the original matrix, but also adds cells around the edge cells. In this way, it is easy to use loops to compare the cells with their 8 neighbors.

Question:
Initialize a N X N board with integer 0, M-1, in which no 3 adjacent cells are the same.
The 3 adjacent cells are might be in horizontal line, vertical line, diagonal line, or L shapes.

Java Code:

Output (one example):
2 1 3 3 0 9 9 1
6 4 7 6 0 4 6 4
9 8 4 0 0 6 0 4
7 7 4 2 6 4 6 0
1 5 7 7 9 2 7 8
8 7 4 0 0 4 8 0
1 0 8 7 6 8 5 8
8 3 7 7 1 8 1 0

found vertical conjuction:0
found right diagonal conjuction:6
found right diagonal conjuction:8
found L sharps face left conjuction:7

2 1 3 3 0 9 9 1
6 4 7 6 1 4 6 4
9 8 4 0 0 1 0 4
7 7 4 2 6 4 6 0
1 5 7 7 9 2 7 8
8 7 4 0 0 4 2 0
1 0 8 7 6 8 5 8
8 3 7 8 1 8 1 0

O Notation:
Time complexity: O(n^2)
Space complexity: O(n^2)

Note: