题目:

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

题解:

这道题很经典,网上有很多讲解实例。
在国际象棋中,皇后最强大,可以横竖斜的走(感谢AI课让我稍微对国际象棋了解了一下)。而八皇后问题就是让8个皇后中的每一个的横竖斜都没有其他皇后,这样其实感觉是一种和棋的状态。。
不知道说的对不对。。。毕竟真实棋盘中不能放8个皇后。。
额。。这道题是N皇后,我说着说着就说到了8皇后去了。。其实是一样的。。。 我这道题的解法也是参考了网上的一些人的讲法。
经典的DFS递归回溯解法,大体思路就是对每一行,按每一列挨个去试,试到了就保存结果没试到就回溯。
难点大概就是用1个一维数组存皇后所在的坐标值。对于一个棋盘来说,每个点都有横纵坐标,用横纵坐标可以表示一个点。
而这道题巧就巧在,每一行只能有一个皇后,也就是说,对于一行只能有一个纵坐标值,所以用1维数组能提前帮助解决皇后不能在同一行的问题。
那么用一维数组表示的话,方法是:一维数组的下标表示横坐标(哪一行),而数组的值表示纵坐标(哪一列)。 例如:对于一个4皇后问题,声明一个长度为4的数组(因为行数为4)。
A[] = [1,0,2,3]表达含义是:
当前4个皇后所在坐标点为:[[,],[,],[,],[,]](被我标蓝的正好是数组的下标,标粉的正好是数组的值)
相当于:A[0] = 1, A[1] = 0, A[2] = 2, A[3] = 3 这样以来,皇后所在的坐标值就能用一维数组表示了。
而正是这个一维数组,在回溯找结果的时候不需要进行remove重置操作了,因为回溯的话正好就回到上一行了,就可以再重新找下一个合法列坐标了。 因为是按照每一行去搜索的,当行坐标值等于行数时,说明棋盘上所有行都放好皇后了,这时就把有皇后的位置标为Q,没有的地方标为0。
按照上面讲的那个一维数组,我们就可以遍历整个棋盘,当坐标为(row,columnVal[row])的时候,就说明这是皇后的位置,标Q就行了。 代码如下:
 1     public ArrayList<String[]> solveNQueens(int n) {
 2         ArrayList<String[]> res = new ArrayList<String[]>();
 3         if(n<=0)
 4             return res;
 5             
 6         int [] columnVal = new int[n];
 7         
 8         DFS_helper(n,res,0,columnVal);
 9         return res;
     }
     
     public void DFS_helper(int nQueens, ArrayList<String[]> res, int row, int[] columnVal){
         if(row == nQueens){
             String[] unit = new String[nQueens];
             for(int i = 0; i < nQueens; i++){
                 StringBuilder s = new StringBuilder();
                 for(int j = 0; j < nQueens; j++){
                     if(j == columnVal[i])
                         s.append("Q");
                     else
                         s.append(".");
                 }
                 
                 unit[i] = s.toString();
             }
             
             res.add(unit);
         }else{
             for(int i = 0; i < nQueens; i++){
                 columnVal[row] = i;//(row,columnVal[row)==>(row,i)
                 
                 if(isValid(row,columnVal))
                     DFS_helper(nQueens, res, row+1, columnVal);
             }
         }
     }
     
     public boolean isValid(int row, int [] columnVal){
         for(int i = 0; i < row; i++){
             if(columnVal[row] == columnVal[i]
                ||Math.abs(columnVal[row]-columnVal[i]) == row-i)
                return false;
         }
         return true;
     }
Reference:
http://zh.wikipedia.org/wiki/%E5%85%AB%E7%9A%87%E5%90%8E%E9%97%AE%E9%A2%98
http://blog.csdn.net/linhuanmars/article/details/20667175
http://blog.csdn.net/u011095253/article/details/9158473

N-Queens leetcode java的更多相关文章

  1. N-Queens II leetcode java

    题目: Follow up for N-Queens problem. Now, instead outputting board configurations, return the total n ...

  2. Regular Expression Matching leetcode java

    题目: Implement regular expression matching with support for '.' and '*'. '.' Matches any single chara ...

  3. Sqrt(int x) leetcode java

    Reference: http://blog.csdn.net/lbyxiafei/article/details/9375735  题目: Implement int sqrt(int x). Co ...

  4. ZigZag Conversion leetcode java

    题目: The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows l ...

  5. [LeetCode][Java]Candy@LeetCode

    Candy There are N children standing in a line. Each child is assigned a rating value. You are giving ...

  6. [Leetcode][JAVA] Valid Palindrome

    Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignori ...

  7. 【目录】LeetCode Java实现

    这里记录一下自己刷的LeetCode题目. 有些博客用英文阐述自己的思路和收获,相当于练习一下英文的表达能力. 比较好的题目有加粗. 1. Two Sum 3. Longest Substring W ...

  8. Single Number II leetcode java

    问题描述: Given an array of integers, every element appears three times except for one. Find that single ...

  9. Scramble String leetcode java

    题目: Given a string s1, we may represent it as a binary tree by partitioning it to two non-empty subs ...

随机推荐

  1. (转)推荐一个在Linux/Unix上架设ASP.NET的 WEB服务器--Jexus

    在Linux/Unix上架设ASP.NET WEB服务器,有两个可选方式,一种是Mono+XSP,一种是Mono+Jexus,其它的方式,比如 Apache+mod_mono.Nginx+FastCg ...

  2. Object类型

    Object类型 我们看到的大多数引用类型值都是Object类型的实例,虽然Object类型不具备多少功能,但是在储存和传输数据上的确是不错的选择. 2.对象字面量表示法 调用Object构造函数: ...

  3. 【leetcode】5. Longest Palindromic Substring

    题目描述: Given a string S, find the longest palindromic substring in S. You may assume that the maximum ...

  4. STL--string(转载)

    string类的构造函数: string(const char *s); //用c字符串s初始化 string(int n,char c); //用n个字符c初始化 此外,string类还支持默认构造 ...

  5. Apache+PHP+MySql 的安装及配置

    每一项技术用的人多了,就会有人将其进行优化,做成一个简单.实用.大众化的工具,这对于初识者来说是非常方便的,但是对于长久学习或工作这方面的人技术人员来说是不可取的,所以还是要学习基础的实用方法.因此, ...

  6. 去掉iphone手机滑动默认行为

    /*去掉iphone手机滑动默认行为*/ $('body').on('touchmove', function (event) { event.preventDefault(); });

  7. eclipse 安装egit 成功后Team中没有显示

    主要是版本不太对. 在http://wiki.eclipse.org/EGit/FAQ#Where_can_I_find_older_releases_of_EGit.3F 中找到对应的版本,设置就O ...

  8. what is the purpose of channel coding?(信道编码的作用?)

    信道.信道编码及其作用 1.信道(channel) 信道和通信电路并不等同,用来表示向某一个方向传送信息的媒体.因此一条通信线路往往包含一条发送信道和一条接收信道. 从通信的双方信息交互方式看有三个基 ...

  9. Django开发网站(二)

    第一课:视图显示 1   建立一个项目:django-admin startproject blog, 进入blog: cd blog 显示:blog(__init__.py settings.py ...

  10. poj 3518 Corporate Identity 后缀数组->多字符串最长相同连续子串

    题目链接 题意:输入N(2 <= N <= 4000)个长度不超过200的字符串,输出字典序最小的最长公共连续子串; 思路:将所有的字符串中间加上分隔符,注:分隔符只需要和输入的字符不同, ...