java 6ms 60% backtracing/good structure to understand


  • 0
    L
    public class Solution {
        public List<List<String>> solveNQueens(int n) {
            if(n == 0)
                return null;
            
            int[] board = new int[n];
            String tmp = "";
            for(int i=0; i < n; ++i)
                tmp += ".";
            List<List<String>> result = new LinkedList<>();
            dfs(board, 0, tmp, result);
            return result;
            
        }
        public void dfs(int[] board, int ind, String tmp, List<List<String>> result){
            for(int i = 0; i < board.length; ++i){
                board[ind] = i;
                if(!checkBoard(board, ind))
                    continue;
                else if(ind == board.length - 1)
                    result.add(transfer(board, tmp));
                else
                    dfs(board, ind+1, tmp, result);
            }
            
        }
        
        
        
        public boolean checkBoard(int[] board, int ind){
            //check the ind location queen
            //board[ind] has been set
            for(int i=0; i < ind; ++i)
                if(board[i] == board[ind]||board[i]-board[ind] == i-ind || board[i]-board[ind] == ind-i)
                    return false;
            return true;
        }
        public List<String> transfer(int[] board, String tmp){
            List<String> result = new LinkedList<>();
            for(int i=0;i<board.length;++i){
                StringBuilder sb = new StringBuilder(tmp);
                sb.setCharAt(board[i], 'Q');
                result.add(sb.toString());
            }
            return result;
        }
        
    }
    

Log in to reply
 

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