Leetcode之回溯法专题-52. N皇后 II(N-Queens II)

Leetcode之回溯法专题-52. N皇后 II(N-Queens II)

 

与51题的代码80%一样,只不过52要求解的数量,51求具体解,点击进入51

 

 

class Solution {
int ans = 0;

    public int totalNQueens(int n) {

        char mp[][] = new char[n][n];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                mp[i][j] = '.';
            }
        }
        dfs(mp, n, 0, 0);
        return ans;
    }

    public void dfs(char[][] mp, int len, int i, int queen) {
        int x = i / len;
        int y = i % len;
        if ((x >= len || y >= len)) {
            if (queen != len)
                return;
            ans++;
            return;
        }
        dfs(mp, len, i + 1, queen);
        if (ok(mp, len, x, y)) {
            mp[x][y] = 'Q';
            dfs(mp, len, i + 1, queen + 1);
            mp[x][y] = '.';
        }

    }

    public boolean ok(char[][] mp, int len, int x, int y) {
        // check row
        for (int i = 0; i < len; i++) {
            if (i == y)
                continue;
            if (mp[x][i] == 'Q')
                return false;
        }

        // check col
        for (int i = 0; i < len; i++) {
            if (i == x)
                continue;
            if (mp[i][y] == 'Q')
                return false;
        }

        // x=1 y=3
        int cnt = 0;
        int up = 0;
        int down = 0;

        for (int i = y + 1; i < len; i++) {
            up = (++cnt) * -1 + x;
            down = cnt * 1 + x;

            if (up < len && up >= 0) {
                // System.out.println("mp[up][i]=["+up+"]["+i+"]");
                if (mp[up][i] == 'Q')
                    return false;
            }

            if (down >= 0 && down < len) {
                // System.out.println("mp[down][i]=["+down+"]["+i+"]");
                if (mp[down][i] == 'Q') {
                    return false;
                }
            }
        }

        // System.out.println("other");
        cnt = 0;
        for (int i = y - 1; i >= 0; i--) {
            up = (++cnt) * -1 + x;
            down = cnt * 1 + x;

            if (up < len && up >= 0) {
                // System.out.println("mp[up][i]=["+up+"]["+i+"]");
                if (mp[up][i] == 'Q')
                    return false;
            }

            if (down >= 0 && down < len) {
                // System.out.println("mp[down][i]=["+down+"]["+i+"]");
                if (mp[down][i] == 'Q') {
                    return false;
                }
            }
        }

        return true;
    }
}

 

posted @ 2019-08-09 01:50  秦羽纶  阅读(215)  评论(0编辑  收藏  举报