码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode :My solution N-Queens

时间:2014-10-01 12:42:01      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   os   ar   java   for   

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.

bubuko.com,布布扣

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

标签:style   blog   http   color   io   os   ar   java   for   

原文地址:http://blog.csdn.net/aresgod/article/details/39717515

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!