Program in c++
MAGIC SQUARES
Backtracking and Recursion
Pretty much any numeric puzzle can be solved with two Boolean methods:
isCompletePuzzle()
// returns true if every spot in the puzzle has a value, false otherwise
isValidPuzzle()
// returns true if the puzzle contains no counterexamples, false otherwise
The solution strategy is implemented in a third method
solvePuzzle()
which executes the following recursive algorithm:
// base cases
Is the puzzle valid? If not, return false.
Is the puzzle complete? If so, return true (valid and complete!)
// current candidate is valid and incomplete, so we have a recursive case
Locate the first blank space in the puzzle.
In a loop over all potential candidates,
Drop in a candidate.
Make a recursive call to solvePuzzle() with the updated puzzle.
Got back a true? Return true.
Otherwise, continue the loop (try the next candidate and make another recursive call)
Completed the loop? None of them worked. Reset the candidate cell to blank and return false.
MAGIC SQUARES
A normal Magic Square of dimensionality n contains the numbers 1 through n2 ordered in such a way that the sum of each row, each column, and each diagonal is the same value. The “magic constant” for such a square is computed as
M = ½ n ( n2 + 1)
For example, here is a magic square of order 3.
8
1
6
3
5
7
4
9
2
The constant is ½ ( 3 ) ( 9 + 1 ) = 15.
HOMEWORK: Magic Square Solver
Write a C++ program that performs the following tasks:
Display a friendly greeting to the user
Prompt the user for a filename (if the file wasn’t provided on the command line)
Accept that filename
Attempt to open the file
Read the numbers in that file
Determine the dimensionality of the puzzle (guaranteed to be a perfect square)
Create a square two-dimensional array containing these values
If there are multiple solutions, stop at the first one found
Create the corresponding Magic Square using the recursive algorithm given
Display the solved puzzle, or an appropriate message if no solution is found
The entries in the file will be base-10 integers.
Display the result using only base-10 numbers.
data inside File for program magicsquare.txt
28 0 0 37 0 0 4 0 27 0 19 0 11 0 0 0 26 43 18 0 0 9 33 1 25 49 17 41 0 0 32 7 24 0 0 0 39 0 31 0 23 0 46 0 0 13 0 0 22
Answers
Answered by
0
Answer:
yes it is right and now follow me
Similar questions
English,
4 months ago
Social Sciences,
4 months ago
Geography,
8 months ago
English,
1 year ago
Chemistry,
1 year ago