首页 > 代码库 > LeetCode--N-Queens

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


LeetCode--N-Queens