Initialize game board in matrix – Code

Initialize game board in matrix is to populate one digit number into a MxN 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.

Matrix is 2D array, which reflects the game in real world. The popular game board questions such as tic tac toe, sudoku, or chess board, all use matrix. Note the cells at the edge has no adjacent cells. So the index should be offset 1 from the edge.

Question:
Initialize a M X N board with integer 0, 10, 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

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)


Download InitializeGameBoard.java
TicTacToe (GitHub)

How to initialize a board game?

(1) Create a mxn matrix (2) write a function to generate random numbers (3) fill the matrix cells with the random numbers (4) write a function to validate whether the values in each cell follow the rules (4) adjust the invalid cells.

Comments are closed