• LeetCode--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.."]
    ]
    原题链接:https://oj.leetcode.com/problems/n-queens/

    题目:n*n的棋盘上放n个皇后,使得不论什么两个皇后不互相攻击。

    思路:递归+回溯。

    import java.util.ArrayList;
    import java.util.List;
    
    public class NQueens {
    	public static void main(String[] args) {
    		List<String[]> result = new NQueens().solveNQueens(5);
    		for(String[] li:result){
    			for(String str : li){
    				System.out.println(str);
    			}
    			System.out.println("----------------");
    		}
    	}
    	public List<String[]> solveNQueens(int n) {
    		List<String[]> result = new ArrayList<String[]>();
    		List<Integer> cols = new ArrayList<Integer>();
    		if(n <= 0)
    			return result;
    		search(result,cols,n);
    		return result;
    	}
    	public void search(List<String[]> result,List<Integer> cols,int n){
    		if(cols.size() == n){
    			result.add(draw(cols));
    			return;
    		}
    		for(int col=0;col<n;col++){
    			if(!isValid(cols,col))
    				continue;
    			cols.add(col);
    			search(result,cols,n);
    			cols.remove(cols.size()-1);
    		}
    	}
    	
    	public String[] draw(List<Integer> cols){
    		String[] chess = new String[cols.size()];
    		for(int i=0;i<chess.length;i++){
    			chess[i] = "";
    			for(int j=0;j<cols.size();j++){
    				if(j==cols.get(i))
    					chess[i] += "Q";
    				else
    					chess[i] += ".";
    			}
    		}
    		return chess;
    	}
    	public boolean isValid(List<Integer> cols,int col){
    		int row = cols.size();
    		for(int i=0;i<row;i++){
    			if(cols.get(i) == col)
    				return false;
    			if(i - cols.get(i) == row - col)
    				return false;
    			if(i+cols.get(i) == row+col)
    				return false;
    		}
    		return true;
    	}
    }
    

    reference:http://www.snip2code.com/Snippet/45053/N-Queens--LeetCode

    http://huntfor.iteye.com/blog/2039013


  • 相关阅读:
    7大python 深度学习框架的描述及优缺点绍
    nodejs 和 js
    python操redis
    python ConfigParser 的小技巧
    RHEL 7.3修改网卡命名规则为ethX
    redhat7.3配置163 yum源
    分区脚本(fdisk)
    linux之sed用法
    linux awk命令详解
    Python 装饰器学习
  • 原文地址:https://www.cnblogs.com/gavanwanggw/p/7069467.html
Copyright © 2020-2023  润新知