N Queen Problem

zhaozj2021-02-16  177

topic:

By the eight queen, the N-Que board is expanded, that is, the N Queo on the N * N board, so that it cannot attack each other, that is, two queen can't be in the same line, the same column or the same slash, how many kinds摆.

analysis:

The problem can be converted to 12345 ... N to satisfy a certain condition (the line is not equal, the column is not equal, just set it is not in the same oblique line, the slope is not 1 or -1).

Code:

Private sub Queensn (Byval n as integer) 'Calculate the process of n Queen issues DIM I as long, J AS INTEGER, K AS INTEGER, NUMBER AS Long, Num as long' cyclic variable DIM FIT AS BOOLEAN 'Determine if it meets the conditions DIM All (), OUT () AS String' for the array of REDIM ALL (1 to n) redim out (1 to n) Number = 1dim Temp1 as long, Temp2 AS Integer 'credit conversion intermediate Variable for i = 1 to nnumber = Number * i 'get n! Nextfor i = 1 to Number' exhaustive N! Arrange ALL (1) = 1TEMP1 = IFOR J = 2 to ntemp2 = temp1 mod j 'mixed credit TEMP1 = TEMP1 / JIF TEMP2 = 0 theall (j) = j 'Temp2 is 0 placed in the last Elsefor K = J to Temp2 1 Step -1all (k) = all (k - 1)' temp2 after the element NEXTALL (TEMP2) = J 'TEMP2 is not 0, which is placed in front ifnext' before the TEMP2 element to get 12345 ... n

Fit = true 'initialization variable

'Cycle to determine whether there are two queen to eat for J = 1 to nfork k = n to 1 step -1if not k = j tell All (k) - all (j) = j - k or all (k) - all (J) = k - j byenfit = falsegoto pass' jumps out of the loop END IFEND IFNEXTNEXT

If Fit Then 'meets the condition Num = Num 1' Output number redim preserve result (1 to num) for j = 1 to nout (j) = String (n, strconv ("□", vbwide))))) MID (OUT J), all (j), 1) = strconv ("Q", vbwide) NextResult (NUM) = "& Num &" method: "& Vbcrlf & Join (OUT, VBCRLF) output NUM N Queen's post-placed state End ifpass: Nextend Sub

Private sub fascist1_click () Dim Result () AS STRINGQUEENSN 9, RESULT 'Nine Queen "D: /Result.txt" for binary as # 1put # 1, JOIN (Result, VBCRLF) Close # 1 msgbox "OK" End Sub

转载请注明原文地址:https://www.9cbs.com/read-7733.html

New Post(0)