LeetCode OJ算法题(五十):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.."]
]
解法:

N皇后问题,用最经典的回溯法求解

这里按照列的顺序来求解,试探当前这一列的Q的位置

1、若Q放在当前的位置是合法的,则试探第二列的Q的位置

2、如果Q放在当前位置是不合法的,则尝试下一种可能,如果这一列中没有合法的Q的位置,则返回到上一列的状态,继续试探

那么如和判断某个皇后的放置位置是否合法呢?只需要查找这一列之前的行,斜线方向有没有放置过Q即可

代码如下:

import java.util.ArrayList;
import java.util.List;


public class No50_NQueens {
	public static void main(String[] args){
		System.out.println(solveNQueens(4));
	}
	public static List<String[]> solveNQueens(int n) {
        List<String[]> ret = new ArrayList<String[]>();
        if(n > 0){
        	char[][] element = new char[n][n];
        	for(int i=0;i<n;i++)
        		for(int j=0;j<n;j++)
        			element[i][j] = '.';
            solve(ret, element, n, 0);
        }
        return ret;
    }
	public static void solve(List<String[]> list, char[][] C, int n, int col){
		for(int i=0;i<n;i++){
			C[i][col] = 'Q';
			if(isLegal(C, i, col)){
				if(col == n-1){
					String[] S = new String[n];
					for(int k=0;k<n;k++)
						S[k] = String.valueOf(C[k]);
					list.add(S);
					C[i][col] = '.';
					continue;
				}
				solve(list, C, n, col+1);
			}
			C[i][col] = '.';
		}
		return;
	}
	public static boolean isLegal(char[][] C, int row, int col){
		for(int j=0;j<col;j++){
			if(C[row][j] == 'Q')
				return false;
		}
		for(int i=row-1,j=col-1;i>=0&&j>=0;i--,j--){
			if(C[i][j] == 'Q')
				return false;
		}
		for(int i=row+1,j=col-1;i<C.length&&j>=0;i++,j--){
			if(C[i][j] == 'Q')
				return false;
		}
		return true;
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值