zoukankan      html  css  js  c++  java
  • N-Queens

    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.

    思路:

      dfs + 回溯 常用模板

    我的代码:

    public class Solution {
        public List<String[]> solveNQueens(int n) {
            if(n <= 0)  return rst;
            char[][] board = new char [n][n];
            for(int i = 0; i < n; i++)
            {
                for(int j = 0; j < n; j++)
                {
                    board[i][j] = '.';
                }
            }
            placeQueens(board, 0, n);
            return rst;
        }
        private List<String[]> rst = new ArrayList<String[]>();
        public void placeQueens(char[][] board, int row, int n)
        {
            //success
            if(row == n)
            {
                String[] strings = new String[n];
                for(int i = 0; i < n ; i++)
                {
                    strings[i] = new String(board[i]);
                }
                rst.add(strings);
                return;
            }
            for(int j = 0; j < n; j++)
            {
                if(canPut(board, row, j, n))
                {
                    board[row][j] = 'Q';
                    placeQueens(board, row + 1, n);
                    board[row][j] = '.';
                }
            }
        }
        public boolean canPut(char [][]board, int x, int y, int n)
        {
            if(x == 0)  return true;
            for(int row = 0; row <= x - 1; row++)
            {
                for(int col = 0; col < n; col++)
                {
                    char c = board[row][col];
                    if(c == '.') continue;
                    else
                    {
                        if(y == col) return false;
                        if(col + row == y + x) return false;
                        if(col - row == y - x) return false;
                    }
                }
            }
            return true;
        }
    }
    View Code
  • 相关阅读:
    交换机实验
    数据模型
    数据库数据的填充规则
    RadComboBox的用法
    数据库中join的用法(on、left。right)
    创建dataTable
    DataSet导出Excel,比以往的方法导出的Excel外观更加好看
    图片下载
    IHTMLDocument2的所有成员、属性、方法、事件[转]
    通过按钮控制左右滚动
  • 原文地址:https://www.cnblogs.com/sunshisonghit/p/4328327.html
Copyright © 2011-2022 走看看