leetCode练习(51)

题目:N-Queens

难度:hard

问题描述:

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.."]
]

解题思路:著名的8皇后问题,要求找到所可行的位置,让所有皇后不会直接攻击到其他皇后。使用回溯法以找到所有的解。基本逻辑为:

1.所有皇后是否已经放置 若放置成功,则将棋盘加入链表,否则到2。

2.查看已经走了几步steps,则在第steps行开始从第0列到n列以此放置新的皇后,放置前判断是否可以放置(未被其他已经存在的皇后攻击),可以的话,则放置新后,返回1.

这里的回溯法注意,每次迭代,不是从下一格开始放置新后,而是从新的一行开始放置新后,这样复杂度从O(n*n)降低到了O(n),从而可以通过提交,否则的话会超时。

具体代码如下:

public class h_51_NQueens {
	public  ArrayList<List<String>> lists=new ArrayList<List<String>>();
	public  LinkedList<String> temp;
	public  List<List<String>> solveNQueens(int n) {	
		if(n==1){
			temp=new LinkedList<String>();
			temp.add("Q");
			lists.add(temp);
			return lists;
		}
		
        char[][] board=new char[n][n];
        for(int i=0;i<n;i++){
        	for(int j=0;j<n;j++){
        		board[i][j]='.';
        	}
        }
        diedai(board,0);  
        return lists;
    }
	public  void diedai(char[][] b,int steps){	
		if(steps==b.length){//所有皇后放完,将棋盘存入lists
			lists.add(boardToList(b));
			return;
		}	
		char[][] boardtemp=new char[b.length][b.length];
		for(int ii=0;ii<b.length;ii++){
			for(int jj=0;jj<b.length;jj++){
				boardtemp[ii][jj]=b[ii][jj];
			}
		}
		for(int n=0;n<b.length;n++){
			if(!this.isvalidate(b, steps, n)){
				continue;
			}else{
				boardtemp[steps][n]='Q';
				diedai(boardtemp,steps+1);
			}
			boardtemp[steps][n]='.';
		}
		
	}
	public boolean isvalidate(char[][] b,int x,int y){
		for(int i=0;i<b.length;i++){
			for(int j=0;j<b.length;j++){
				if(b[i][j]=='Q'&&(x==i||y==j||(Math.abs(i-x)==Math.abs(j-y)))){
					return false;
				}
			}
		}
		return true;
	}
	public  List<String> boardToList(char[][]b){//将棋盘转为list<String>
		String str;
		temp=new LinkedList<String>();
		for(int i=0;i<b.length;i++){
			str=new String(b[i]);
			temp.add(str);
		}
		System.out.println("solution:");
		for(int i=0;i<temp.size();i++){
			System.out.println(temp.get(i));
		}
		return temp;
	}
	
	public static void main(String[]args){
		h_51_NQueens s=new h_51_NQueens();
		s.solveNQueens(4);
	}
}


                                                                                                                         

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值