Clean concise Java code


  • 1
    Y
    public class Solution {
        // 依次枚举每一行皇后的位置,在这个枚举过程中确保不会在每一列、每一条斜线上出现两个皇后。
        public List<List<String>> solveNQueens(int n) {
            List<List<String>> result = new ArrayList<>();
            if (n <= 0) {
                return result;
            }
            int[] queens = new int[n];
            helper(n, queens, 0, result);
            
            return result;  
        }
        
        void helper(int n, int[] queens, int row, List<List<String>> res) {
            if (row == n) {
                // add to res based on queens
                List<String> list = new ArrayList<>();
                for (int i = 0; i < n ; i++) {
                    StringBuilder sb = new StringBuilder();
                    for (int j = 0; j < n; j++) { 
                        if (queens[i] == j) {
                            sb.append("Q");
                        } else {
                            sb.append(".");
                        }
                    }
                    list.add(sb.toString());
                }
                res.add(list);
                return; 
            }
            
            for (int col = 0; col < n; col++) {
                if (isValid(queens, row, col)) {
                    queens[row] = col;
                    helper(n, queens, row+1, res);
                    queens[row] = -1;
                }
            }
        }
        
        boolean isValid(int[] queens, int row, int col) {
            for (int i = 0; i < row; i++) {
                // the queen at row i has col queens[i]
                if (queens[i] == col || (Math.abs(row-i) == Math.abs(col-queens[i]))) {
                    return false;   
                }
            }
            return true; 
        }
    }```

  • 0

    Confused about check conditon:
    queens[i] == j; and the purpose of queens[],
    could you please enlighten me


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.