zoukankan      html  css  js  c++  java
  • 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


  • 相关阅读:
    Hadoop 学习笔记 (十) hadoop2.2.0 生产环境部署 HDFS HA Federation 含Yarn部署
    hadoop 2.x 安装包目录结构分析
    词聚类
    Hadoop 学习笔记 (十一) MapReduce 求平均成绩
    Hadoop 学习笔记 (十) MapReduce实现排序 全局变量
    Hadoop 学习笔记 (九) hadoop2.2.0 生产环境部署 HDFS HA部署方法
    Visual Studio Code 快捷键大全(Windows)
    Eclipse安装教程 ——史上最详细安装Java &Python教程说明
    jquery操作select(取值,设置选中)
    $.ajax 中的contentType
  • 原文地址:https://www.cnblogs.com/gavanwanggw/p/7069467.html
Copyright © 2011-2022 走看看