Java standard dfs backtracking, easy to understand


  • 0
    D
    public class Solution {
        
        char[][] board;
        int n;
        
        public List<List<String>> solveNQueens(int n) {
            
            board = new char[n][n];
            this.n = n;
            
            //init the board
            for (int i=0; i<n; i++) 
                for (int j=0; j<n; j++)
                    board[i][j] = '.';
                
            List<String> path = new LinkedList<>();
            List<List<String>> ret = new LinkedList<>();
            
            dfs(n, 0, path, ret);
            
            return ret;
        }
        
        //standard dfs backtracking
        void dfs(int n, int start, List<String> path, List<List<String>> ret) {
            if (path.size() == n) {
                ret.add(new LinkedList<String>(path));
                return;
            }
            
            for (int i=0; i<n; i++) {
                if (!isValid(start, i)) {
                    continue;
                }
                board[start][i] = 'Q';
                String str=new String(board[start]);
                path.add(str);
                dfs(n, start+1, path, ret);
                path.remove(path.size()-1);
                board[start][i] = '.';
            }
        }
        
        //valid if this cell is valid
        boolean isValid(int row, int col) {
            for (int i=0; i<n; i++) {
                if (board[i][col] == 'Q')
                    return false;
            }
    
            for (int i=0; i<n; i++) {
                if (board[row][i] == 'Q')
                    return false;
            }
            
            for (int i=row, j=col; i>=0 && j>=0; i--, j--) {
                if (board[i][j] == 'Q')
                    return false;
            }
            
            for (int i=row, j=col; i<n && j<n; i++, j++) {
                if (board[i][j] == 'Q')
                    return false;
            }
            
            for (int i=row, j=col; i<n && j>=0; i++, j--) {
                if (board[i][j] == 'Q')
                    return false;
            }
            
            for (int i=row, j=col; i>=0 && j<n; i--, j++) {
                if (board[i][j] == 'Q')
                    return false;
            }
            
            return true;
        }
    }
    

Log in to reply
 

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