zoukankan      html  css  js  c++  java
  • [CareerCup] 9.9 Eight Queens 八皇后问题

    9.9 Write an algorithm to print all ways of arranging eight queens on an 8x8 chess board so that none of them share the same row, column or diagonal. In this case, "diagonal" means all diagonals, not just the two that bisect the board.

    LeetCode上的原题,请参见我之前的博客N-Queens N皇后问题N-Queens II N皇后问题之二

    class Solution {
    public:
        vector<vector<int> > placeQueens(int n) {
            vector<vector<int> > res;
            vector<int> pos(n, -1);
            placeQueensDFS(pos, 0, res);
            return res;
        }
        void placeQueensDFS(vector<int> &pos, int row, vector<vector<int> > &res) {
            int n = pos.size();
            if (row == n) res.push_back(pos);
            else {
                for (int col = 0; col < n; ++col) {
                    if (isValid(pos, row, col)) {
                        pos[row] = col;
                        placeQueensDFS(pos, row + 1, res);
                        pos[row] = -1;
                    }
                }
            }
        }
        bool isValid(vector<int> &pos, int row, int col) {
            for (int i = 0; i < row; ++i) {
                if (col == pos[i] || abs(row - i) == abs(col - pos[i])) {
                    return false;
                }
            }
            return true;
        }
    };
  • 相关阅读:
    图书管理系统
    关键路径
    最短路径

    最小生成树、最短路径
    Huffman编码
    LA 3401
    UVA 10881
    OI 刷题记录——每周更新
    4396: [Usaco2015 dec]High Card Wins
  • 原文地址:https://www.cnblogs.com/grandyang/p/4845827.html
Copyright © 2011-2022 走看看