• Leetcode08.12 N皇后


     

    public List<List<String>> solveNQueens(int n) {
            //棋盘
            char[][] board = new char[n][n];
            //结果集合
            List<List<String>> reList = new LinkedList<List<String>>();
            setQueen(0, n, board, reList);
            return reList;
        }
    
        //回溯函数,逐行放置皇后
        private final void setQueen(int x, int boardLen, char[][] board, List<List<String>> reList) {
            if (x == boardLen) {
                reList.add(boardToString(board, boardLen));
                return;
            }
            for (int i = 0; i < boardLen; i++) {
                if (!canSet(x, i, boardLen, board)) {
                    continue;
                }
                board[x][i] = 'Q';
                setQueen(x + 1, boardLen, board, reList);
                board[x][i] = '.';
            }
        }
    
        //判断 x,y 坐标是否可以放置皇后
        private final boolean canSet(int x, int y, int boardLen, char[][] board) {
            for (int i = 0; i <= x; i++) {
                //判断竖线
                if (board[i][y] == 'Q') {
                    return false;
                }
                int point = x - i;
                //判断左下对角线
                if (inBoard(i, y - point, boardLen) && (board[i][y - point] == 'Q')) {
                    return false;
                }
                //判断右下对角线
                if (inBoard(i, y + point, boardLen) && board[i][y + point] == 'Q') {
                    return false;
                }
            }
            return true;
        }
    
        //判断 x,y 坐标是否在棋盘内
        private final boolean inBoard(int x, int y, int boardLen) {
            if (x >= 0 && y >= 0 && x < boardLen && y < boardLen) {
                return true;
            }
            return false;
        }
    
        //将棋盘转为 String 集合
        private final List<String> boardToString(char[][] board, int boardLen) {
            List<String> re = new ArrayList<String>(boardLen);
            for (int i = 0; i < boardLen; i++) {
                StringBuilder sb = new StringBuilder();
                for (int j = 0; j < boardLen; j++) {
                    char ch = board[i][j] == 'Q' ? 'Q' : '.';
                    sb.append(ch);
                }
                re.add(sb.toString());
            }
            return re;
        }

  • 相关阅读:
    转:matplotlib画图,plt.xx和ax.xx之间有什么差异
    转:Python __call__()方法,可调用对象
    训练集,验证集,测试集,交叉验证
    Visio画图和导出图的时候,去除多余白色背景
    在线jupyter notebook
    dfs序
    codeforces 877b
    codeforce864d
    codeforce868c
    查看本地git查看git公钥,私钥的方式
  • 原文地址:https://www.cnblogs.com/niuyourou/p/13383139.html
Copyright © 2020-2023  润新知