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
  • 相关阅读:
    bat 笔记 一
    air 桌面应用发布后可以删除的文件
    as3 去掉字符串空白问题
    as3 air 获取文件夹下的所有文件
    egret 配置设置
    egret 精简游戏项目
    starling 第一天
    《笨办法学Python》 第2课手记
    《笨办法学Python》 第1课手记
    《笨办法学Python》 第0课手记
  • 原文地址:https://www.cnblogs.com/sunshisonghit/p/4328327.html
Copyright © 2011-2022 走看看