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

LeetCode: N-Queens II 解题报告

2014-12-18 18:14 399 查看
N-Queens II (LEVEL 4 难度级别,最高级5)

Follow up for N-Queens problem.

public class Solution {
public int totalNQueens(int n) {
if (n == 0) {
return 0;
}

// Bug 1: forget to modify the parameters of the function.
return dfs(n, 0, new ArrayList<Integer>());
}

public int dfs(int n, int row, ArrayList<Integer> path) {
if (row == n) {
// The base case: 当最后一行,皇后只有1种放法(就是不放)
return 1;
}

int num = 0;

// The queen can select any of the slot.
for (int i = 0; i < n; i++) {
if (!isValid(path, i)) {
continue;
}
path.add(i);

// All the solutions is all the possiablities are add up.
num += dfs(n, row + 1, path);
path.remove(path.size() - 1);
}

return num;
}

public boolean isValid(ArrayList<Integer> path, int col) {
int size = path.size();
for (int i = 0; i < size; i++) {
// The same column with any of the current queen.
if (col == path.get(i)) {
return false;
}

// diagonally lines.
// Bug 2: forget to add a ')'
if (size - i == Math.abs(col - path.get(i))) {
return false;
}
}

return true;
}
}


View Code

GITHUB:

https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/dfs/totalNQueens_1218_2014.java
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: