1. 程式人生 > >LeetCode--N-Queens

LeetCode--N-Queens

empty pub ++ courier reference arraylist ons () else

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