(writing this article is mainly tomorrow exam, algorithm exam, today do not want to review, Xiang today also opened the blog, so on this platform to review, should be more efficient. Finally wish me to test a good result tomorrow. Hehe ... )
The problem of n Queens is mainly applied to backtracking methods. First select a path to calculate, if the condition is not satisfied, the backtracking, select another path to calculate.
I think backtracking: just want to be in the maze, first select a road to go, if you can not walk through, return, in the choice of the intersection of the place, choose other intersections, if you can walk through, it means that the path selection is correct. That means finding a way to solve the problem.
The following code analysis and resolution:
Problem analysis, n queen problem, problem analysis Needless to say, mainly for pseudo-code analysis and solution. Different rows, different columns, not on the same slash.
Apply to Sparks language
(1) Judge whether a place can place a queen
Procedure Place (k)
Global X (k); integer i,k;//x (l) Place the Queen's sequence, subscript is the Queen's Row, X (i) is the column placed by the Queen
i<-1;
For I<k do
If x (i) =x (k) or ABS (i-k) =abs (X (i)-X (k))//Determine whether the K-Queens clash with the K-1 queen in front. ABS: is to judge whether on the same slash.
Then return (false)
endif
i<-i+1;
Repeat
return (true);
End Place
(2) Solving the problem of n Queens
Procedure Nqueens (N)
Global K,n,x (1:N)//k is the current row, X (k) is the current column
X (1) <-0; k<-1;
While k>0 do//the following actions for all rows
X (k) <-x (k) +1//move to the next column
While X (k) <=n and is place (k) do//if the current position cannot be moved to the next column
X (k) <-x (k) +1
Repeat
The current position can be placed
If X (k) <=n//the current column must satisfy less than n
Then if k=n//is judged as a complete solution.
Then print (X)//Yes, the output solution
else K<-k+1,x (k) <-0;//No, move to the next row, column from the beginning
endif
Else k<-k-1//is not satisfied, which means that the solution is not satisfied. So the backtracking.
endif
Repeat
End Nqueens
···············································································································
Well, a problem has been solved. Here's a look back.
This question is not so troublesome to understand. What are the places to pay attention to tomorrow's exams?
One way to go to the end, hit the south wall back, find another path.
Finally, I'll get a good result tomorrow. The next algorithm is analyzed and calculated. Come on!!!!
Algorithm one n Queen problem