[leetcode] N-Queens

本文介绍了一种使用回溯算法解决N皇后问题的方法,并提供了两种不同的实现方案。通过递归地放置皇后并检查冲突,最终生成所有可能的不冲突配置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

from : https://leetcode.com/problems/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.."]
]

思路 : 

回溯,用一个char数组queue存放已经排好的皇后的位置,然后寻找新的位置。

public class Solution {
    private List<List<String>> solutions;
    private char[] dots;

    public List<List<String>> solveNQueens(int n) {
    	init(n);
    	
        int[] queue = new int[n];
        // queue[i]=k means the ith line and kth column has the Queue
        
        traverse(queue, 0, n);
        
        return solutions;
    }

	private void traverse(int[] queue, int k, int n) {
		if(k == n) {
			generate(queue);
		}
		
		for(int i=0; i<n; ++i) {
			boolean valid = true;
			for(int j=0; j<k; ++j) {
				if(i == queue[j] || Math.abs(queue[j]-i) == k-j) {
					// if same column of diagonal
					valid = false;
					break;
				}
			}
			
			if(valid) {
				queue[k] = i;
				traverse(queue, k+1, n);
			}
		}
		
	}
	
	private void generate(int[] queue) {
		List<String> q = new ArrayList<String>();
		for(int i=0, len = queue.length; i<len; ++i) {
			int idx = queue[i];
			dots[idx] = 'Q';
			q.add(new String(dots));
			dots[idx] = '.';
		}
		solutions.add(q);
	}
	
	private void init(int n) {
    	solutions = new ArrayList<List<String>>();
    	dots = new char[n];
    	for(int i=0; i<n; ++i) {
    		dots[i] = '.';
    	}
	}
}


public class Solution {

	private List<List<String>> ans = null;
	private int N = 0;
	private int[] position = null;
	private char[] dots = null;

	public List<List<String>> solveNQueens(int n) {
		if (n < 1) {
			return new ArrayList<List<String>>();
		}
		init(n);
		takeRow(0);
		return ans;
	}

	private void takeRow(int k) {
		if (k == N) {
			addToAns();
			return;
		}
		for (int j = 0; j < N; ++j) {
			boolean valid = true;
			for (int i = 0; i < k && valid; ++i) {
				if (position[i] == j || Math.abs(position[i] - j) == k - i) {
					valid = false;
				}
			}
			if (valid) {
				position[k] = j;
				takeRow(k + 1);
			}
		}
	}

	private void addToAns() {
		List<String> one = new ArrayList<String>();
		for (int i = 0; i < N; ++i) {
			int j = position[i];
			dots[j] = 'Q';
			one.add(new String(dots));
			dots[j] = '.';
		}
		ans.add(one);
	}

	private void init(int n) {
		N = n;
		ans = new ArrayList<List<String>>();
		position = new int[n];
		dots = new char[n];
		Arrays.fill(dots, '.');
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值