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
原创粉丝点击