LeetCode 52. N皇后 II

浪矢清發表於2020-10-17

這一週要準備位元組的面試,所以只貼程式碼,面試完之後補充完整

class Solution {
public:
    void setZero(vector<vector<int>>& board, int layer, int col, int n) {
        for (int i = 0; i < n; i++) {
            board[layer][i] = 0;
            board[i][col] = 0;
        }
        for (int i = 0; i + col < n && i + layer < n; i++)
            board[layer + i][col + i] = 0;
        for (int i = 0; col - i >= 0 && layer - i >= 0; i++)
            board[layer - i][col - i] = 0;
        for (int i = 0; i + col < n && layer - i >= 0; i++)
            board[layer - i][col + i] = 0;
        for (int i = 0; col - i >= 0 && layer + i < n; i++)
            board[layer + i][col - i] = 0;
        board[layer][col] = 9;
    }

    void move(vector<vector<int>> board, int& cnt, int layer, int n) {
        for (int i = 0; i < n; i++) {
            vector<vector<int>> hisBoard(board);
            if (hisBoard[layer][i] == 1 && layer == n - 1) {
                cnt++;
                return;
            }
            else if (hisBoard[layer][i] == 1) {
                setZero(hisBoard, layer, i, n);
                //show(hisBoard);
                move(hisBoard, cnt, layer + 1, n);
            }
        }
    }

    int totalNQueens(int n) {
        int cnt = 0;
        vector<vector<int>> board;
        for (int i = 0; i < n; i++) {
            vector<int> tmp(n, 1); //1代表可以落子
            board.emplace_back(tmp);
        }
        //show(board);

        move(board, cnt, 0, n);
        return cnt;
    }
};

 

相關文章