题解 | #N皇后问题#
N皇后问题
https://www.nowcoder.com/practice/c76408782512486d91eea181107293b6
import java.util.*;
public class Solution {
/**
*
* @param n int整型 the n
* @return int整型
*/
public int Nqueen (int n) {
byte[][] map = new byte[n][n];
return getCount(map, 0, n);
}
private int getCount(byte[][] map, int row, int n) {
int count = 0;
for (Integer i = 0; i < n; i++) {
count += seatCount(map, row, i, n);
clearRow(map, row);
}
return count;
}
private int seatCount(byte[][] map, int row, int seat, int n) {
if (!pass(map, row, seat, n)) {
return 0;
}
map[row][seat] = 1;
if (n - 1 == row) {
return 1;
}
return getCount(map, row + 1, n);
}
private void clearRow(byte[][] map, int row) {
Arrays.fill(map[row], (byte) 0);
}
private boolean pass(byte[][] map, int row, int seat, int n) {
if (row == 0) {
return true;
}
for (int i = 0, px = row; i < row; i++, px--) {
// 同列排除
if (map[i][seat] == 1) {
return false;
}
int lx = seat - px;
int rx = seat + px;
// 左斜角排除
if (lx >= 0 && map[i][lx] == 1) {
return false;
}
// 右斜角排除
if (rx < n && map[i][rx] == 1) {
return false;
}
}
return true;
}
}
查看12道真题和解析