您的位置:首页 > 产品设计 > UI/UE

leetcode N-Queens II

2014-11-16 17:44 337 查看
N-Queens II 原题地址:
https://oj.leetcode.com/problems/n-queens-ii/
Follow up for N-Queens problem.

Now, instead outputting board configurations, return the total number of distinct solutions.



和N Queens类似,稍作改动即可。
public class Solution {
int count = 0;
public int totalNQueens(int n) {
if (n == 0)
return count;
char[][] queens = new char

;
boolean[][] check = new boolean

;
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++) {
queens[i][j] = '.';
check[i][j] = true;
}
helpSolve(queens, check, 0);
return count;
}

private void helpSolve(char[][] queens, boolean[][] check, int column) {
if (column == queens.length) {
count++;
return;
}
for (int row = 0; row < queens.length; row++) {
if (check[row][column]) {
queens[row][column] = 'Q';
boolean[][] _check = updateCheck(check, row, column);
helpSolve(queens, _check, column+1);
queens[row][column] = '.';
}
}
}

private boolean[][] updateCheck(boolean[][] check, int row, int column) {
int len = check.length;
boolean[][] uc = new boolean[len][len];
for (int _i = 0; _i < len; _i++)
for (int _j = 0; _j < len; _j++)
uc[_i][_j] = check[_i][_j];
for (int _i = 0; _i < len; _i++)
uc[_i][column] = false;
for (int _j = 0; _j < len; _j++)
uc[row][_j] = false;
for (int _i = row + 1, _j = column + 1; _i < len && _j < len; _i++, _j++)
uc[_i][_j] = false;
for (int _i = row + 1, _j = column - 1; _i < len && _j >= 0; _i++, _j--)
uc[_i][_j] = false;
for (int _i = row - 1, _j = column + 1; _i >= 0 && _j < len; _i--, _j++)
uc[_i][_j] = false;
for (int _i = row - 1, _j = column - 1; _i >= 0 && _j >= 0; _i--, _j--)
uc[_i][_j] = false;
return uc;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java leetcode 回溯