LeetCode进阶之路(N-Queens)
来源:互联网 发布:如何筛选excel数据求和 编辑:程序博客网 时间:2024/06/08 02:06
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皇后的问题,采用回溯法。有不明白的直接看回溯这篇文章(http://blog.csdn.net/yulingkai88/article/details/52108264)
关于N-Queens II,只是求数量,size就可以。
public class Solution { // static int p = 0; static int num; static int[] location; static List<List<String>> list = new ArrayList<List<String>>(); public List<List<String>> solveNQueens(int n) { num = n; location = new int[n+1]; findQueen(1); return list; } public void findQueen(int t) {//t表示第几行 if(t > num) { // p++;//如果大于8,则找到一个解,输出 List<String> l = new ArrayList<String>(); for(int i = 1;i < num+1;i++) { StringBuffer st = new StringBuffer(); for(int j = 1;j <= num;j++) { if(j == location[i]){ st.append("Q"); } else { st.append("."); } } l.add(st.toString()); } list.add(l); } else { for(int i = 1; i <= num;i++) {//下一个节点有n个选择 location[t] = i;//a[t]表示第几列 if(isValid(t)) {//符合皇后规则,继续寻找下一个节点。不符合,则寻找下一列. findQueen(t+1); } } } } public boolean isValid(int t){//判断是否合法,即两个皇后既不能在同一行同一列同一斜线。 for(int i = 1;i < t;i++) { if(Math.abs(t-i) == Math.abs(location[t]-location[i]) || location[i] == location[t]){ return false; } } return true; }
0 0
- LeetCode进阶之路(N-Queens)
- LeetCode之N-Queens
- leetcode之路051 N-Queens
- LeetCode OJ 之 N-Queens(N皇后)
- LeetCode OJ 之 N-Queens II(N皇后 - 二)
- LeetCode(51) N-Queens
- leetcode 刷题之路 94 N-Queens
- leetcode 刷题之路 95 N-Queens II
- leetcode系列(60)N-Queens, N-Queens II
- LeetCode 51. N-Queens(N皇后)
- LeetCode第51题之 N-Queens
- LeetCode进阶之路(Pow(x, n))
- 【LeetCode】N-Queens && N-Queens II
- leetcode N-Queens & N-Queens II
- Leetcode: N-Queens && N-Queens II
- 【Leetcode】【python】N-Queens/N-Queens II
- Leetcode题解(7)L51/N-Queens
- LeetCode 题解(104): N-Queens
- activiti-explorer乱码问题的解决
- 堆排序-java
- 设计模式:备忘录模式(Memento)
- php代码编写规范
- 嵌入式物联网应用开发-远程温度监控
- LeetCode进阶之路(N-Queens)
- VPS安全之iptables基本配置
- 设计模式:观察者模式(Observer)
- activiti-rest的权限控制
- NOI2012 美食节 动态加边维护费用流
- 第2章 获得文本语料和词汇资源
- Myeclipse中weblogic配置
- Q48:不能被继承的类 ——学习笔记
- 第九届湖南省大学生程序设计竞赛部分题解