JAVA------------Easy Version To Understand!!!!!!!


  • 0
    H
    public static boolean checkOK(int[] columnNumber, int row) {
    	for (int i = 0; i < row; i++) {
    		if (columnNumber[i] == columnNumber[row]
    				|| Math.abs(i - row) == Math.abs(columnNumber[i] - columnNumber[row]))
    			return false;
    	}
    	return true;
    }
    
    public static void DFS(int n, int row, List<List<String>> result, List<String> sequence, int[] columnNumber) {
    	if (row == n) {
    		for (int i = 0; i < n; i++) {
    			StringBuffer s = new StringBuffer();
    			for (int j = 0; j < n; j++) {
    				if (columnNumber[i] == j)
    					s.append("Q");
    				else
    					s.append(".");
    			}
    			sequence.add(s.toString());
    		}
    		result.add(new ArrayList<String>(sequence));
    		sequence.clear();//
    
    	} else {
    		for (int i = 0; i < n; i++) {
    			columnNumber[row] = i;
    			if (checkOK(columnNumber, row)) {
    				DFS(n, row + 1, result, sequence, columnNumber);
    			}
    		}
    	}
    }
    
    public static List<List<String>> solveNQueens(int n) {
    	if (n <= 0)
    		return new ArrayList<List<String>>();
    	List<List<String>> result = new ArrayList<List<String>>();
    	List<String> sequence = new ArrayList<String>();
    	int[] columnNumber = new int[n];//
    	DFS(n, 0, result, sequence, columnNumber);
    	return result;
    }

Log in to reply
 

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