Leetcode: N Queen I & II

来源:互联网 发布:three.js下载 编辑:程序博客网 时间:2024/05/10 16:08

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

 Solve the problem on leetcode

首先我们弄清楚一下输出,最终输出是ArrayList<String[]>,每一个解是String[], 每一个解的每一行是String

我们当然可以采用上一题,Word Search里更新board内容的方法,不过更新来更新去比较麻烦,这一题我们换个思路

我们把这一题分成几个小问题

1. 传统的dfs递归

2. 验证放置Queen的地方是否合法

3. 输出Board结果

这么做的好处就是,一开始,我们不用建立一个庞大的Board,我们选用一个数组对应Board里面的每一行,数组每一个值对应这一行放置Queen的列号

比如: int[ ] {3,1,4,2} 代表放置的地点分别为[1,3], [2,1], [3,4], [2,4] 这么一来,我们用很简单的用数组表示了整个Board,而且在isValid函数里判断的时候会非常简洁,而且把输出Board单独隔离了出来

下面是代码

public class Solution {    public ArrayList<String[]> solveNQueens(int n) {        ArrayList<String[]> res = new ArrayList<String[]>();        int[] loc = new int[n];        dfs(res,loc,0,n);        return res;    }        public void dfs(ArrayList<String[]> res, int[] loc, int cur, int n){        if(cur==n)             printboard(res,loc,n);        else{            for(int i=0;i<n;i++){                loc[cur] = i;                if(isValid(loc,cur))                    dfs(res,loc,cur+1,n);            }        }    }        public boolean isValid(int[] loc, int cur){        for(int i=0;i<cur;i++){            if(loc[i]==loc[cur]||Math.abs(loc[i]-loc[cur])==(cur-i))                return false;        }        return true;    }        public void printboard(ArrayList<String[]> res, int[] loc, int n){        String[] ans = new String[n];        for(int i=0;i<n;i++){            String row = new String();            for(int j=0;j<n;j++){                if(j==loc[i]) row += "Q";                else row += ".";            }            ans[i] = row;        }        res.add(ans);    }}

来分析一下代码:

dfs的循环是指这一行里,从第一列到最后一列放置的所有可能,如果放置的地点通过isValid验证,通过cur+1进入下一行进行递归, 如果没通过验证,试下一个位置,如果所有位置都不Valid,跳回上一层

采用int[ ]的好处是,每一次我们只需改变一个数字就相当于改变了棋子的放置位置

isValid函数,首先int[ ]代表行,这样就避免了每一行出现重复的Queen (因为你不可能在一个int里面放2个值)这样简化了验证 接下来我们只需验证列和对角线

验证列的时候,要验证这一行之前的行有没有重复的(注意是验证之前的喔)

验证对角线,根据对角线性质,长 = 宽 那么我们不难写出 Math.abs(loc[i] - loc[cur]) == (cur - i) 

最后loc[]里面记录的是解的信息(如果有解)我们把它转换成String, 输出Board即可


Queen II

变成了统计解的个数的问题:

Follow up for N-Queens problem. Now, instead outputting board configurations, return the total number of distinct solutions.

Solve the problem on leetcode

public class Solution {    int res;     public int totalNQueens(int n) {        res = 0;        if(n<=0) return res;        int[] loc = new int[n];        dfs(loc,0,n);        return res;    }        public void dfs(int[] loc, int cur, int n){        if (cur==n) {            res+=1;            return;        }        for(int i=0;i<n;i++){            loc[cur] = i;            if(isValid(loc,cur))                dfs(loc,cur+1,n);        }    }        public boolean isValid(int[] loc, int cur){        for(int i=0;i<cur;i++){            if(loc[i]==loc[cur]||Math.abs(loc[i]-loc[cur])==(cur-i))                return false;        }        return true;    }}

同样的思路,代码反而比Queen I 要简单,记得把res声明在totalNQueens外面

原创粉丝点击