Leetcode no. 51

来源:互联网 发布:ubuntu 画图工具 编辑:程序博客网 时间:2024/05/17 04:44

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.."]]

public class Solution {    public List<List<String>> solveNQueens(int n){        List<List<String>> list= new LinkedList<List<String>>();        solveNQueens(0, 0, n, new int[n], list);        return list;    }    private void solveNQueens(int row, int col, int n, int[] column, List<List<String>> l){        if (row == n){            List<String> sub= new LinkedList<>();            for (int j = 0; j < n; j++) {                StringBuilder sb= new StringBuilder("");                for (int k = 0; k < column[j]; k++) { sb.append(".");}                sb.append("Q");                for (int k = column[j]+1; k < n; k++) { sb.append(".");}                sub.add(sb.toString());            }            l.add(sub);        }        else{            for (int i = col; i < n; i++) {                column[row]= i;                boolean f= true;                for (int r = row-1, lc= i-1, rc= i+1; r>=0 ; r--,lc--,rc++ ) {                    if (column[r]== i || column[r]==lc || column[r]==rc) f= false;                }                if (f) solveNQueens(row+1, 0, n, column, l);            }        }    }}


0 0