首页 > 代码库 > LeetCode :My solution N-Queens
LeetCode :My solution N-Queens
N-Queens
Total Accepted: 15603 Total Submissions: 60198My SubmissionsThe 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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。