my concise solution


  • 0
    X

    public static List<List<String>> solveNQueens(int n) {
    List<List<String>> all = new ArrayList<List<String>>();
    if (n <= 0)
    return all;
    char[][] cc = new char[n][n];

    	for (int i = 0; i < n; i++) {
    		Arrays.fill(cc[i], '.');
    	}
    
    	queens(all, cc, new int[n], 0);
    	return all;
    }
    
    public static void queens(List<List<String>> all, char[][] cc, int[] cols,
    		int row) {
    	if (row >= cc.length) {
    		List<String> cl = new ArrayList<>();
    		for (int i = 0; i < cc.length; i++) {
    			cl.add(new String(cc[i]));
    		}
    		all.add(cl);
    		return;
    	}
    
    	for (int i = 0; i < cc[0].length; i++) {
    
    		boolean isLine = false;
    		// 验证是否处于同一列
    		for (int r = 0; r < row; r++) {
    			if (i - cols[r] == 0
    					|| Math.abs(row - r) == Math.abs(i - cols[r])) {
    				isLine = true;
    				break;
    			}
    		}
    
    		if (isLine)
    			continue;
    		cols[row] = i;
    
    		cc[row][i] = 'Q';
    		// 遍历下一个值
    		queens(all, cc, cols, row + 1);
    		cc[row][i] = '.';
    	}
    
    }

Log in to reply
 

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