[LeetCode] N-Queens
来源:互联网 发布:软件过程能力 编辑:程序博客网 时间:2024/06/16 02:02
Total Accepted: 7379 Total Submissions: 29099
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 ArrayList<String[]> solveNQueens(int n) { ArrayList<String[]> list = new ArrayList<String[]>(); int[] path = new int[n]; dfs(list, path, n, 0); return list; } public void dfs(ArrayList<String[]> list, int[] path, int n, int level) { if (level == n) { String[] set = new String[n]; for (int i = 0; i < n; i++) { StringBuffer str = new StringBuffer(); for (int j = 0; j < n; j++) { if (path[i] == j) str.append("Q"); else str.append("."); } set[i] = str.toString(); } list.add(set); return; } for (int i = 0; i < n; i++) { path[level] = i; if (check(path, level)) dfs(list, path, n, level + 1); } } public boolean check(int[] path, int level) { for (int i = 0; i < level; i++) { if ((path[i] == path[level]) || Math.abs(path[i] - path[level]) == (level - i)) return false; } return true; }}
0 0
- 【LeetCode】N-Queens && N-Queens II
- leetcode N-Queens & N-Queens II
- Leetcode: N-Queens && N-Queens II
- 【Leetcode】【python】N-Queens/N-Queens II
- LeetCode: N-Queens II
- LeetCode: N-Queens
- LeetCode : N-Queens
- LeetCode : N-Queens II
- [Leetcode] N-Queens II
- leetcode 72: N-Queens
- LeetCode 38: N-Queens
- 【leetcode】N-Queens II
- 【leetcode】N-Queens
- LeetCode: N Queens II
- [LeetCode]N-Queens
- [LeetCode]N-Queens II
- [leetcode]N-Queens
- [LeetCode] Anagrams、N-Queens
- 项目开发积累(技术)
- 《linux 内核完全剖析》编译linux 0.12 内核 Ubuntu 64bits 环境
- java "群发"聊天demo
- Android_imageviewChange
- IOS开源APP应用
- [LeetCode] N-Queens
- 自己的抽屉
- udhcp源码详解(三)上 之配置信息的读取
- Reveal代理配置
- 修改ActionMenu的背景色和文字颜色
- 三种方式配置Mac OS X的启动项
- ZigBee2006 CC2430 按键流程
- 淘宝购物设计
- SVN