Moderate algorithm | 33. N Queens Problem

Title Description

n is an n-queens problem queens n * n placed on the board, can not attack each other Queen each other (any two Queens not in the same row, same column, the same oblique lines).

Given an integer n, returns all solutions to different problems of the Queen of n.

Each solution includes placing a clear layout Queen n, wherein "Q" and "." Respectively represent one queen and one empty position.

Sample 1

输入:1
输出:
   [["Q"]]

Sample 2

输入:4
输出:
[
  // Solution 1
  [".Q..",
   "...Q",
   "Q...",
   "..Q."
  ],
  // Solution 2
  ["..Q.",
   "Q...",
   "...Q",
   ".Q.."
  ]
]

java solution to a problem

Search violence, try to place can be placed, each program can return

class Solution {
    List<List<String>> solveNQueens(int n) {
        List<List<String>> results = new ArrayList<>();
        if (n <= 0) {
            return results;
        }
        
        search(results, new ArrayList<Integer>(), n);
        return results;
    }
    
    /*
     * results store all of the chessboards
     * cols store the column indices for each row
     */
    private void search(List<List<String>> results,
                        List<Integer> cols,
                        int n) {
        if (cols.size() == n) {
            results.add(drawChessboard(cols));
            return;
        }
        
        for (int colIndex = 0; colIndex < n; colIndex++) {
            if (!isValid(cols, colIndex)) {
                continue;
            }
            cols.add(colIndex);
            search(results, cols, n);
            cols.remove(cols.size() - 1);
        }
    }
    
    private List<String> drawChessboard(List<Integer> cols) {
        List<String> chessboard = new ArrayList<>();
        for (int i = 0; i < cols.size(); i++) {
            StringBuilder sb = new StringBuilder();
            for (int j = 0; j < cols.size(); j++) {
                sb.append(j == cols.get(i) ? 'Q' : '.');
            }
            chessboard.add(sb.toString());
        }
        return chessboard;
    }
    
    private boolean isValid(List<Integer> cols, int column) {
        int row = cols.size();
        for (int rowIndex = 0; rowIndex < cols.size(); rowIndex++) {
            if (cols.get(rowIndex) == column) {
                return false;
            }
            if (rowIndex + cols.get(rowIndex) == row + column) {
                return false;
            }
            if (rowIndex - cols.get(rowIndex) == row - column) {
                return false;
            }
        }
        return true;
    }
}

C ++ solution to a problem

Search violence, try to place can be placed, each program can return

class Solution {
public:
    vector<vector<string> > solveNQueens(int n) {
        // write your code here
        vector<vector<string> > result;
        if( n <= 0 )
        {
            return result;
        }
        vector<int> cols;
        search(n, cols, result);
        return result;
    }
    
    void search(int n, vector<int> &cols, vector<vector<string> > &result)
    {
        if(cols.size() == n)
        {
            result.push_back(drawResult(cols, n));
            return;
        }
        for(int col = 0; col < n; col++)
        {
            if(!isValid(cols, col))
            {
                continue;
            }
            cols.push_back(col);
            search(n, cols, result);
            cols.pop_back();
        }
    }
    bool isValid(vector<int> &cols, int col)
    {
        int row = cols.size();
        for(int i = 0; i < row; ++i)
        {
            if(cols[i] == col)
            {
                return false;
            }
            if(i - cols[i] == row - col)
            {
                return false;
            }
            if(i + cols[i] == row + col)
            {
                return false;
            }
        }
        return true;
    }
    
    vector<string> drawResult(vector<int> &cols, int n)
    {
        vector<string> result;
        for(int i = 0; i < cols.size(); ++i)
        {
            string temp(n, '.');
            temp[cols[i]] = 'Q';
            result.push_back(temp);
        }
        return result;
    }
};

python problem solution

Type arrangement with a depth-first search algorithm.

class Solution:
    def solveNQueens(self, n):
        results = []
        self.search(n, [], results)
        return results
        
    def search(self, n, cols, results):
        row = len(cols)
        if row == n:
            results.append(self.draw_chessboard(cols))
            return

        for col in range(n):
            if not self.is_valid(cols, row, col):
                continue
            cols.append(col)
            self.search(n, cols, results)
            cols.pop()
            
    def draw_chessboard(self, cols):
        n = len(cols)
        board = []
        for i in range(n):
            row = ['Q' if j == cols[i] else '.' for j in range(n)]
            board.append(''.join(row))
        return board
        
    def is_valid(self, cols, row, col):
        for r, c in enumerate(cols):
            if c == col:
                return False
            if r - c == row - col or r + c == row + col:
                return False
        return True
Published 153 original articles · won praise 20 · views 5410

Guess you like

Origin blog.csdn.net/qq_43233085/article/details/104086246