题解 | #N皇后问题#

N皇后问题

http://www.nowcoder.com/practice/c76408782512486d91eea181107293b6

import java.util.*;


public class Solution {
    int[][] chessboard;
    int sum = 0;
    /**
     *
     * @param n int整型 the n
     * @return int整型
     */
    public int Nqueen (int n) {
        // write code here
        if (n == 1) {
            return 1;
        }
        chessboard = new int[n][n];
        goNext(0, n);
        return sum;
    }

    private void goNext(int row, int n) {
        //终止条件
        if (row == n) {
            //说明已经走通
            sum++;
        } else {
            for (int i = 0; i < n; i++) {
                if (check(n, row, i)) {
                    //如果这个可以放,那就走下一步
                    chessboard[row][i] = 1;
                    goNext(row + 1, n);
                    //回溯
                    chessboard[row][i] = 0;
                }
            }
        }
    }

    public boolean check(int n, int x, int y) {
        //1.判断左上方向有无棋子
        for (int i = x, j = y; i >= 0 && j >= 0; i--, j--) {
            if (chessboard[i][j] == 1) {
                return false;
            }
        }
        //2.判断右上方向有无棋子
        for (int i = x, j = y; i >= 0 && j < n; i--, j++) {
            if (chessboard[i][j] == 1) {
                return false;
            }
        }
        //3.判断上方有无棋子
        for (int i = x; i >= 0; i--) {
            if (chessboard[i][y] == 1) {
                return false;
            }
        }
        return true;
    }
}

全部评论

相关推荐

牛客383479252号:9,2学生暑期实习失利开始投小厂,给这群人整自信了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务