[Leetcode 52] N-queens II
| COMMENTS
Question
Link
Follow up for n-queens problem.
Now, instead outputting board configurations and return the total number of distinct solutions.
Stats
| Frequency |
3 |
| Difficulty |
4 |
| Adjusted difficulty |
2 |
| Time to use |
——– |
Ratings/color = 1 (white) 2 (lime) 3 (yellow) 4/5 (red)
Solution
I posted 2 solution by me. Second code is same as this guy ' s code.
My Code
Using global variable (similar to [Leetcode] n-queens)
1 Public classSolution {2 intres = 0;//Res should is global, cause Java func cannot return int value back.3 Public intTotalnqueens (intN) {4 //int res = 0;5 //int[] Col4row = new Int[n];6Helper (n, 0,New int[n]);7 returnRes;8 }9 Ten Private voidHelperintNintRowint[] col4row) { One if(row = = N) {//All positions is OK A++Res; - return;//Don't forget to quit from this recursion. - } the for(inti = 0; I < n; i++) { -Col4row[row] = i;//put every col to this row to test the correctness. - if(check (row, Col4row)) { -Helper (n, row+1, Col4row); + } - } + } A at Private BooleanCheckintRowint[] col4row) { - for(inti = 0; i < row; i++) { - if(Col4row[i] = = Col4row[row] | | -Math.Abs (Col4row[i]-col4row[row]) = = row-i) - return false; - } in return true; - } to}
Without using global variable,
Public classSolution { Public intTotalnqueens (intN) {returnSolve (0, N,New int[n]); } Private intSolveintRowintNint[] col4row) { if(row = = N)return1; intAns = 0; for(inti = 0; I < n; i++) { BooleanConflict =false; for(intj = 0; J < Row; J + +) //Check First, if not OK and go to next col, if ok let col4row[row] = i; if(i = = Col4row[j] | | row-j = = Math.Abs (i-Col4row[j])) Conflict=true; if(conflict)Continue; Col4row[row]=i; Ans+ = Solve (row + 1, N, Col4row); //This row was finished, go to next row } returnans; }}
8.18 [Leetcode] N-queens II