-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathSolution.java
More file actions
77 lines (70 loc) · 2.33 KB
/
Copy pathSolution.java
File metadata and controls
77 lines (70 loc) · 2.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/**
* Time : O(); Space: O()
* @tag : Backtracking
* @by : Steven Cooks
* @date: Jun 3, 2015
***************************************************************************
* Description:
*
* A queen can attack other queen in the same row,
* same column and diagonal line.
*
***************************************************************************
* {@link https://leetcode.com/problems/n-queens/ }
*/
package _051_NQueens;
import java.util.ArrayList;
import java.util.List;
/** see test {@link _051_NQueens.SolutionTest } */
public class Solution {
public List<String[]> solveNQueens(int n) {
List<String[]> result = new ArrayList<String[]>();
if (n <= 0) {
return result;
}
int iQueen = 0;
// queenPos[i] = j means placing the ith Queen at board[i][j]
int[] queenPos = new int[n];
solveNQueens(iQueen, n, queenPos, result);
return result;
}
private void solveNQueens(int iQueen, int nQueen, int[] queenPos,
List<String[]> result) {
if (iQueen == nQueen) {
// construct board
String[] board = new String[nQueen];
for (int i = 0; i < board.length; i++) {
StringBuilder row = new StringBuilder();
for (int j = 0; j < nQueen; j++) {
if (queenPos[i] == j) {
row.append("Q");
} else {
row.append(".");
}
}
board[i] = row.toString();
}
result.add(board);
return;
}
int row = iQueen;
for (int col = 0; col < nQueen; col++) {
// try to put the ith Queen at board[row][col]
queenPos[row] = col;
if (isBoardOk(row, queenPos)) {
solveNQueens(iQueen + 1, nQueen, queenPos, result);
}
}
}
private boolean isBoardOk(int row, int[] queenPos) {
for (int i = 0; i < row; i++) {
if (queenPos[i] == queenPos[row] // queens in the same column
|| Math.abs(queenPos[row] - queenPos[i]) == row - i) // diagonal
// line
{
return false;
}
}
return true;
}
}