Leetcode no. 51
来源:互联网 发布:ubuntu 画图工具 编辑:程序博客网 时间:2024/05/17 04:44
51. N-Queens
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<List<String>> solveNQueens(int n){ List<List<String>> list= new LinkedList<List<String>>(); solveNQueens(0, 0, n, new int[n], list); return list; } private void solveNQueens(int row, int col, int n, int[] column, List<List<String>> l){ if (row == n){ List<String> sub= new LinkedList<>(); for (int j = 0; j < n; j++) { StringBuilder sb= new StringBuilder(""); for (int k = 0; k < column[j]; k++) { sb.append(".");} sb.append("Q"); for (int k = column[j]+1; k < n; k++) { sb.append(".");} sub.add(sb.toString()); } l.add(sub); } else{ for (int i = col; i < n; i++) { column[row]= i; boolean f= true; for (int r = row-1, lc= i-1, rc= i+1; r>=0 ; r--,lc--,rc++ ) { if (column[r]== i || column[r]==lc || column[r]==rc) f= false; } if (f) solveNQueens(row+1, 0, n, column, l); } } }}
0 0
- Leetcode no. 51
- LeetCode No.51 N-Queens
- LeetCode No.11 ~No.12
- Leetcode NO.78 Subsets
- Leetcode NO.77 Combinations
- Leetcode NO.46 Permutations
- 【leetcode】No. 235 LCABST
- LeetCode no. 35
- Leetcode no. 37
- Leetcode no. 279
- Leetcode no. 335
- Leetcode no. 283
- Leetcode no. 181 (sql)
- Leetcode no. 40
- Leetcode no. 238
- Leetcode no. 26
- Leetcode no. 80
- Leetcode no. 228
- iOS CocoaPods之 Pods 制作(新版方式)
- 安凯AK3918E加载mtk7601驱动不能ifconfig wlan0 down
- java垃圾回收机制
- 封装CLLocationManager定位获取经纬度
- 问题:viewController不会调用dealloc()不会销毁
- Leetcode no. 51
- Android中Button自定义外观-按下与放开时不同背景
- iOS Block的基本使用以及Block传值
- 山寨web服务器
- 分布式事务操作之Spring+JTA+mybatis
- java.lang.NumberFormatException: For input string: "on"
- vs开发工具一个统计行数的正则使用方法
- 在与SQLServer建立连接时出现与网络相关的或特定于实例的错误
- iOS UItextField去除空格