52. N-Queens II(N-皇后II)

题目链接:https://leetcode.com/problems/n-queens-ii/

这道题比51题还要简单些,直接在上题代码上修改了一些。

AC 4ms Java:

class Solution {
    private int ans=0;
    public int totalNQueens(int n) {
        String[][] strs=new String[n][n];
        for(int i=0;i<n;i++)
            for(int j=0;j<n;j++)
                strs[i][j]=".";//初始化二维数组
        backtrace(0,n,strs);
        return ans;
    }
    public void backtrace(int row,int n,String[][] strs){
        if(row>n-1){//当行数大于N-1时,说明已经找到了一组解。
            ans++;
        }
        for(int col=0;col<n;col++){
            if(check(strs,row,col)){//检查通过时,继续递归下一行
                strs[row][col]="Q";
                backtrace(row+1,n,strs);
                strs[row][col]=".";//注意别忘了再更新回来。
            }
        }
    }
    public boolean check(String[][] strs,int row,int col){
        int n=strs.length;
        for(int t=0;t<n;t++){//检查列冲突
            if(strs[t][col].equals("Q"))
                return false;
        }
        for(int t=0;t<n;t++){//检查行冲突
            if(strs[row][t].equals("Q"))
                return false;
        }
        for(int i=row-1,j=col-1;i>=0&&j>=0;i--,j--){
            if(strs[i][j].equals("Q"))//检查左上对角线冲突
                return false;
        }
        for(int i=row-1,j=col+1;i>=0&&j<n;i--,j++){
            if(strs[i][j].equals("Q"))//检查右上对角线冲突
                return false;
        }
        return true;
    }
}

_________________________________________________________________________________________________________________________________二更的华丽分割线————————————————————————————————

后来我拿char数组试了一下,速度比String数组快不少,(让人又爱又恨的String啊)

AC 2ms Java :

class Solution {
    private int ans=0;
    public int totalNQueens(int n) {
        char[][] chars=new char[n][n];
        for(int i=0;i<n;i++)
            for(int j=0;j<n;j++)
                chars[i][j]='.';//初始化二维数组
        backtrace(0,n,chars);
        return ans;
    }
    public void backtrace(int row,int n,char[][] chars){
        if(row>n-1){//当行数大于N-1时,说明已经找到了一组解。
            ans++;
            return;
        }
        for(int col=0;col<n;col++){
            if(check(chars,row,col)){//检查通过时,继续递归下一行
                chars[row][col]='Q';
                backtrace(row+1,n,chars);
                chars[row][col]='.';//注意别忘了再更新回来。
            }
        }
    }
    public boolean check(char[][] chars,int row,int col){
        int n=chars.length;
        for(int t=0;t<n;t++){//检查列冲突
            if(chars[t][col]=='Q')
                return false;
        }
        for(int t=0;t<n;t++){//检查行冲突
            if(chars[row][t]=='Q')
                return false;
        }
        for(int i=row-1,j=col-1;i>=0&&j>=0;i--,j--){
            if(chars[i][j]=='Q')//检查左上对角线冲突
                return false;
        }
        for(int i=row-1,j=col+1;i>=0&&j<n;i--,j++){
            if(chars[i][j]=='Q')//检查右上对角线冲突
                return false;
        }
        return true;
    }
}

猜你喜欢

转载自blog.csdn.net/God_Mood/article/details/88016829