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

LeetCode--N-Queens

时间:2017-06-23 14:15:29      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:main   border   overflow   []   .com   conf   tac   tom   ica   

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


LeetCode--N-Queens

标签:main   border   overflow   []   .com   conf   tac   tom   ica   

原文地址:http://www.cnblogs.com/gavanwanggw/p/7069467.html

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