sitinlab1_nqueens.pptx

advertisement
Sit-In Lab 1
Ob-CHESS-ion
N-Queens Puzzle Checker
• Famous N-Queens puzzle
• You want to check if the input solution is correct
• No 2 queens can be on the same row, column or
diagonal
• Write a piece of code to verify the solution
• Input:
– N – Number of rows ( Number of queens on chessboard )
– Followed by N rows of N numbers
• 0 – Empty space
• 1 – Queen
• Output whether the puzzle is a valid solution
Example – Valid?
Output :
Example – Incorrect solution
Output : INVALID
Example – Valid Solution
Output : VALID
No other queen in same row, column and
diagonal
Algorithm
• Loop through each square of the array:
– Start from the top left, iterate row by row
– For each queen found
• Starting from the square on its right, check if there exists
another queen in the same row
• Starting from the square right below it, check if there
exists another queen in the same column
• Starting from the square on its bottom right, check if
there exists another queen in the same right diagonal
• Starting from the square on its bottom left, check if
there exists another queen in the same left diagonal
– Return false if there exists another queen
Visualisation – Start from top left
Visualisation – Queen is found, check rows and
diagonals
Visualisation – Queen is found, check rows and
diagonals
Valid
Visualisation – Iterate row by row
- No queen in this space
Visualisation – Another Queen is found
Visualisation – Queen is found, check rows and
diagonals
Valid
Visualisation – Iterate row by row
Visualisation – Another Queen is found
Visualisation – Queen is found, check rows and
diagonals
Invalid
Visualisation – Break from loop and return false
Invalid
• Main method:
– Read in the inputs
– Call helper methods and print the output
• Helper methods:
– Check rows, columns and diagonals ( 4
directions ), returning false if another queen is
found
– Check if given coordinates are out of array
bounds ( >= N )
How to check diagonals?
0 1 2 3 4 5 6 7
0
1
2
3
4
5
6
7
[1][3]
0 1 2 3 4 5 6 7
0
1
2
3
4
5
6
7
[2][4]
0 1 2 3 4 5 6 7
0
1
2
3
4
5
6
7
[3][5]
0 1 2 3 4 5 6 7
0
1
2
3
4
5
6
7
[3][5]
Row++
Col++
0 1 2 3 4 5 6 7
0
1
2
3
4
5
6
7
[1][3]
0 1 2 3 4 5 6 7
0
1
2
3
4
5
6
7
[2][2]
0 1 2 3 4 5 6 7
0
1
2
3
4
5
6
7
[3][1]
0 1 2 3 4 5 6 7
0
1
2
3
4
5
6
7
[3][1]
Row++
Col--
Questions?
Download