`

LeetCode 51 - N-Queens

 
阅读更多

The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.

Given an integer n, return all distinct solutions to the n-queens puzzle.

Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space respectively.

For example,
There exist two distinct solutions to the 4-queens puzzle:

[
 [".Q..",  // Solution 1
  "...Q",
  "Q...",
  "..Q."],

 ["..Q.",  // Solution 2
  "Q...",
  "...Q",
  ".Q.."]
]

Solution:

 

We will use a backtracking algorithm For each row, the column where we want to put the queen is based on checking that it does not violate the required condition

1, For this, we need to store the column of the queen in each row as soon as we have finalized it. Let ColumnForRow[] be the array which stores the column number for each row

2, The checks that are required for the three given conditions are:
» On same Column : ColumnForRow[i] == ColumnForRow[j]
» On same Diagonal: abs( ColumnForRow[i] - ColumnForRow[j] ) == abs( i - j )

private int[] col4Row;
private char[] placement;
public List<String[]> solveNQueens(int n) {
    col4Row = new int[n];
    placement = new char[n];
    Arrays.fill(placement, '.');
    List<String[]> result = new ArrayList<>();
    placeQueen(result, 0, n);
    return result;
}

public void placeQueen(List<String[]> result, int row, int n) {
    if(row == n) {
        String[] solution = new String[n];
        for(int i=0; i<col4Row.length; i++) {
            int col = col4Row[i];
            placement[col] = 'Q';
            solution[i] = new String(placement);
            placement[col] = '.';
        }
        result.add(solution);
    } else {
        for(int i=0; i<n; i++) {
            col4Row[row] = i;
            if(check(row)) {
                placeQueen(result, row+1, n);
            }
        }
    }
}

public boolean check(int row) {
    for(int i=0; i<row; i++) {
        int diff = Math.abs(col4Row[i] - col4Row[row]);
        if(diff == 0 || diff == row - i) return false;
    }
    return true;
}

 

C++的版本1:

vector<vector<string>> solveNQueens(int n) {
    vector<vector<string>> res;
    vector<int> col4Row(n);
    solve(res, col4Row, 0);
    return res;
}

void solve(vector<vector<string>>& res, vector<int>& col4Row, int row) {
    int n = col4Row.size();
    if(row == n) {
        vector<string> v;
        for(auto col: col4Row) {
            string s(n, '.');
            s[col] = 'Q';
            v.push_back(s);
        }
        res.push_back(v);
        return;
    }
    for(int i=0; i<n; i++) {
        col4Row[row] = i;
        if(check(col4Row, row)) {
            solve(res, col4Row, row+1);
        }
    }
}

bool check(vector<int>& col4Row, int row) {
    int col = col4Row[row];
    for(int i=0; i<row; i++) {
        int diff = abs(col4Row[i] - col4Row[row]);
        if(!diff || diff == row-i) return false;
    }
    return true;
}

 

C++的版本2,使用Lamda表达式:

vector<vector<string>> solveNQueens(int n) {
    vector<vector<string>> res;
    vector<int> col4Row(n);
    
    auto check = [&](int row) {
        int col = col4Row[row];
        for(int i=0; i<row; i++) {
            int diff = abs(col4Row[i] - col4Row[row]);
            if(!diff || diff == row-i) return false;
        }
        return true;
    };
    
    function<void(int)> solve = [&](int row){
        if(row == n) {
            vector<string> v;
            for(auto col: col4Row) {
                string s(n, '.');
                s[col] = 'Q';
                v.push_back(s);
            }
            res.push_back(v);
            return;
        }
        for(int i=0; i<n; i++) {
            col4Row[row] = i;
            if(check(row)) {
                solve(row+1);
            }
        }
    };
    
    solve(0);
    return res;
}

 

分享到:
评论

相关推荐

    leetcode71python-leetcode:leetcode

    leetcode 71 Python用 Python 编写 Leetcode (数据科学家的解决方案) - 易于理解的最佳解决方案,可以通过所有 Leetcode 测试用例,对于非 ...leetcode ...leetcode ...N-Queens (HARD) Leetcode 52. N-

    leetcode530-leetcode-practice:练习力码

    leetcode 530 力码练习 前 250 个问题 1 二和 :check_mark: 3 无重复字符的最长子串 :check_mark: 4 两个有序数组的中位数 5 最长回文子串 7 反转整数 8 字符串到整数 (atoi) 10 正则表达式匹配 11 盛水的容器 12 ...

    leetcode530-LeetCode:力码

    leetcode ...N-Queens II 最大子阵列 螺旋矩阵 跳跃游戏 合并间隔 插入间隔 螺旋矩阵 II 排列顺序(无法访问文章) 61-70 轮换名单 独特的路径 独特的路径 II 最小路径和(无法访问文章) 有效号码 加一

    leetcode中国-Leetcode:Leetcode的生活经历:)

    leetcode中国力码 我的 Leetcode 生活经历! 我创建了这个存储库来分享我对 leetcode 问题的解决方案。 另外,我会补充一下我在解决问题时的想法,也会补充一些简单的测试用例以供...N-Queens(硬) 56. 合并间隔(中)

    leetcode信封-leet:我的leetcode练习的回购

    N-Queens 572 另一棵树的子树98 验证二叉搜索树1048 最长的字符串链101 对称树第151话第177话218 天际线问题242 有效字谜378 排序矩阵中的第 K 个最小元素第489章 扫地机器人406按高度重构队列592 分数加减法920 ...

    javalruleetcode-leetcode-oo:我使用面向对象设计的leetcode实现

    N 个节点 中等的 20 有效括号 简单的 21 合并两个排序列表 简单的 22 生成括号 中等的 23 合并 k 个排序列表 难的 26 从排序数组中删除重复项 简单的 27 删除元素 简单的 30 连接所有单词的子串 难的 32 最长有效...

    最大公共字符串leetcode-LeetCodeSolultionBook:力码解决方案书

    最大公共字符串leetcode 这本书的在线版本可以在 [gitbook.com] 上查看 进步写作 104 二叉树的最大深度 111 二叉树的最小深度 174 地牢游戏 84 直方图中最大的矩形 85 最大矩形 198 强盗 第213话 第42章 截留雨水 11...

    leetcode力扣是什么-leetcode:leetcodebytags按自己整理的一些类别

    leetcode力扣是什么 leetcode-按类别 看了一些leetcode刷题指南,总结一下两个重点,一是...N-Queens (hard) 132 Palindrome Partitioning (hard) 212 Word Search II (hard) DFS /二叉树 the difference between df

    javalruleetcode-leetcode:我对leetcode挑战的解决方案

    N-Queens II 59.44% 97 交错串 TLE 146 LRU缓存 83.44% 174 地牢游戏 100% 的 Go 提交 354 俄罗斯娃娃信封 23.99% 中等评价 数量 问题 殴打 2 添加两个数字 35.18% 3 无重复字符的最长子串 79.27% 5 最长回文子串 87...

    Leetcode:更大的LeetcodeLösungen

    49组Anagrams视频讲解50 Pow(x,n)视频讲解51 N-Queens视频讲解52 N-Queens II视频讲解53最大子数组视频讲解54螺旋矩阵视频讲解55跳转游戏视频讲解56合并间隔视频讲解57插入间隔视频讲解59螺旋矩

    leetcode

    51 NQueens(硬) 126单词阶梯II(困难) 贪心算法 腐败心算法是指在对问题转化时,总是造成在当前看来是最好的选择。如此,不从整体最优上考虑,只造成在某种意义上的局部最优解。贪心算法不是对所有问题都能得到...

Global site tag (gtag.js) - Google Analytics