首页 > 代码库 > LeetCode :My solution N-Queens

LeetCode :My solution N-Queens

N-Queens

 Total Accepted: 15603 Total Submissions: 60198My Submissions

The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.

Given an integer n, return all distinct solutions to the n-queens puzzle.

Each solution contains a distinct board configuration of the n-queens‘ placement, where ‘Q‘ and ‘.‘ both indicate a queen and an empty space respectively.

For example,
There exist two distinct solutions to the 4-queens puzzle:

[
 [".Q..",  // Solution 1
  "...Q",
  "Q...",
  "..Q."],

 ["..Q.",  // Solution 2
  "Q...",
  "...Q",
  ".Q.."]
]
public class Solution {
  public List<String[]> solveNQueens(int n) {
        List<String[]> result = new ArrayList<String[]>();
        if ( n < 1) {
            return result ;
        }
        List<List<Integer>> storeArray = new ArrayList<List<Integer>>();
        helper(n, new ArrayList<Integer>(), storeArray);
		result = drawPicture(storeArray,n);
        return result;
    }
    
    private List<String[]> drawPicture(List<List<Integer>> storeArray ,int n) {
    	List<String[]> drawedPicture = new ArrayList<String[]> ();
    	for (int i = 0; i < storeArray.size();i++) {
    		String[] str = new String[n];
    		for (int j = 0; j < n; j++) {
    		    str[j] = new String("");
    			for (int w = 0; w < n; w++) {
    				if (storeArray.get(i).get(j) == w) {
    					str[j] +="Q";
    				} else {
    					str[j] +=".";
    				}
    			}
    			
    		}
    		drawedPicture.add(str);
    	}
    	return drawedPicture;
	}

	boolean isValid(ArrayList<Integer> cols, int col) {
    	   int newX = col;
    	   int newY = cols.size();
    	for (int y = 0; y < cols.size(); y++) {
    		int x = cols.get(y);
    		
    		if (newX == x) {
    			return false;
    		}
    		if (newX - newY == x - y) {
    			return false;
    		}
    		if (newX + newY == x + y){
    			return false;
    		}
    	}
    	return true;
    }
    public void helper(int n, ArrayList<Integer> cols,  List<List<Integer>> storeArray) {
    	if (cols.size() == n) {
    		storeArray.add(new ArrayList<Integer>(cols));
    		return;
    	}
    	for (int i = 0; i < n; i++) {
    		if (!isValid(cols, i)) {
    			continue;
    		}
    		cols.add(i);
    		helper(n, cols, storeArray);
    		cols.remove(cols.size() - 1);
    	}
    }
}


LeetCode :My solution N-Queens