Download presentation
Presentation is loading. Please wait.
1
Sit-In Lab 1 Ob-CHESS-ion
2
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
3
Example – Valid? Output :
4
Example – Incorrect solution
Output : INVALID
5
Example – Valid Solution
Output : VALID
6
No other queen in same row, column and diagonal
7
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
8
Visualisation – Start from top left
9
Visualisation – Queen is found, check rows and diagonals
10
Visualisation – Queen is found, check rows and diagonals
Valid
11
Visualisation – Iterate row by row
- No queen in this space
12
Visualisation – Another Queen is found
13
Visualisation – Queen is found, check rows and diagonals
Valid
14
Visualisation – Iterate row by row
15
Visualisation – Another Queen is found
16
Visualisation – Queen is found, check rows and diagonals
Invalid
17
Visualisation – Break from loop and return false
Invalid
18
Main method: Helper methods: 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 )
19
How to check diagonals?
20
1 2 [1][3] 3 4 5 6 7
21
1 2 [2][4] 3 4 5 6 7
22
1 2 3 4 5 6 7 [3][5]
23
1 2 3 4 5 6 7 [3][5] Row++ Col++
24
1 2 [1][3] 3 4 5 6 7
25
1 2 [2][2] 3 4 5 6 7
26
1 2 3 4 5 6 7 [3][1]
27
1 2 3 4 5 6 7 [3][1] Row++ Col--
28
Questions?
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.