A typical C++ (8ms) solution using C++11 lambda


  • 0
    Y
        vector<vector<string>> solveNQueens(int n) {
            vector<vector<string>> ans;
            vector<string> board(n, string(n,'.'));
            vector<int> queen_col(n);
            auto valid_queen = [&board, &queen_col](int i, int j) {
                for(int r=0; r<i; ++r) {
                    if(queen_col[r] == j || abs(j-queen_col[r]) == abs(i-r)) return false;
                }
                return true;
            };
            
            function<void(int)> solve = [&](int row_idx) {
                if(n==row_idx) ans.push_back(board);
                for(int col=0; col<n; ++col) {
                    if(valid_queen(row_idx, col)) {
                        board[row_idx][col] = 'Q';
                        queen_col[row_idx] = col;
                        solve(row_idx+1);
                        board[row_idx][col] = '.';
                    }
                }
            };
            solve(0);
            return ans;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.