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

微笑、不失礼 提交于 2019-11-26 15:04:18

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;
    }
}

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!