码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode]51 N-Queens

时间:2015-01-03 08:14:06      阅读:214      评论:0      收藏:0      [点我收藏+]

标签:leetcode   np   

https://oj.leetcode.com/problems/n-queens/

http://blog.csdn.net/linhuanmars/article/details/20667175

public class Solution {
    public List<String[]> solveNQueens(int n) {
        
        List<String[]> result = new ArrayList<>();
        int[] qcols = new int[n];
        solve(n, 0, qcols, result);
        return result;
        
    }
    
    private void solve(int n, // number of queen
                       int row, // current row iteration, [0 -> n-1]
                       int[] qcols, // describing queens positions
                       List<String[]> result)
    {
        if (row == n)
        {
            // all [0, n-1] has fulfilled, a solution found.
            result.add(toBoard(qcols));
            return;
        }
        
        // We are on row
        // try to put Q in each columns, and check
        for (int i = 0 ; i < n ; i ++)
        {
            qcols[row] = i;
            boolean valid = checkBoard(qcols, row);
            if (valid)
            {
                // Enter next iteration
                solve(n, row + 1, qcols, result);
            }
        }
    }
    
    // 此方法检查新增的Q(row)是否符合已有的棋盘
    // 因为一行只保存一个Q的位置,所以行一定符合
    // 检查列:qcols[i] != qcols[row]
    // 检查对角线 abs(i - row) != abs(qcols[i] - qcols[row])
    // Check new Q(on row) can fit existing board.
    private boolean checkBoard(int[] qcols, int row)
    {
        for (int i = 0 ; i < row ; i ++)
        {
            if ((qcols[i] == qcols[row]) ||
               Math.abs(i - row) == Math.abs(qcols[i] - qcols[row]))
               return false;
        }
        return true;
    }

    // Build the board.    
    private String[] toBoard(int[] qcols)
    {
        int n = qcols.length;
        String[] b = new String[n];
        for (int i = 0 ; i < n ; i ++)
        {
            int qcol = qcols[i];
            StringBuilder sb = new StringBuilder();
            for (int j = 0 ; j < qcol ; j ++)
                sb.append(".");
            sb.append("Q");
            for (int j = qcol + 1 ; j < n ; j ++)
                sb.append(".");
            b[i] = sb.toString();
        }
        return b;
    }
}


[LeetCode]51 N-Queens

标签:leetcode   np   

原文地址:http://7371901.blog.51cto.com/7361901/1598586

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!