51. N-Queens && 52. N-Queens II
2016-01-12 20:47
369 查看
The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.
N皇后问题,不能有两个皇后在同一行、列、斜线。两个题一个要求返回结果,一个要求返回解的个数。
DFS。
N皇后问题,不能有两个皇后在同一行、列、斜线。两个题一个要求返回结果,一个要求返回解的个数。
DFS。
List<List<String>> r = new ArrayList<List<String>>(); public List<List<String>> solveNQueens(int n) { char[][] q = new char ; for(int i = 0;i < n;i++){ for(int j = 0;j < n;j++){ q[i][j] = '.'; } } boolean[] col = new boolean ; //标记该列有没有被皇后占领 boolean[] d1 = new boolean[2*n]; //标记该斜线有没有被皇后占领 boolean[] d2 = new boolean[2*n]; nQueens(n,q,0,col,d1,d2); return r; } private void nQueens(int n, char[][] q,int row,boolean[] col,boolean[] d1,boolean[] d2){ if (row == n) { //success List<String> tmp = new ArrayList<String>(); for(char[] c:q){ tmp.add(new String(c)); } r.add(tmp); return; } for (int j = 0; j < n; j++) { int td1 = row+j , td2 = j - row+n; if(col[j] || d1[td1] || d2[td2]) continue; col[j] = true; d1[td1] = true; d2[td2] = true; q[row][j] = 'Q'; nQueens(n, q, row+1,col,d1,d2); col[j] = false; d1[td1] = false; d2[td2] = false; q[row][j] = '.'; } }
int num; public int totalNQueens(int n) { boolean[] col = new boolean ; //标记该列有没有被皇后占领 boolean[] d1 = new boolean[2*n]; //标记该斜线有没有被皇后占领 boolean[] d2 = new boolean[2*n]; nQueens(n,0,col,d1,d2); return num; } private void nQueens(int n,int row,boolean[] col,boolean[] d1,boolean[] d2){ if (row == n) { //success num++; //计数 return; } for (int j = 0; j < n; j++) { int td1 = row+j , td2 = j - row+n; if(col[j] || d1[td1] || d2[td2]) continue; col[j] = true; d1[td1] = true; d2[td2] = true; nQueens(n, row+1,col,d1,d2); col[j] = false; d1[td1] = false; d2[td2] = false; } }
相关文章推荐
- SpannableStringBuilder实现图文混排
- uiautomator的坑和AAPT命令方式启动一个应用程序
- 蓝懿IOS学习UICollectionView实战轮播图
- 小菊花和UITextField
- easyui异步
- uiimageView 的图片拉伸问题的解决办法
- UITableView 笔记
- UI课程(ScrollView)
- UIAutomator输入中文
- Android EditText 的<requestFocus />用于点击tab键或enter键焦点自动进入下一个输入框
- 一个基于 EasyUI 的前台架构(5)右键快捷菜单
- iOS开发UI篇—Quartz2D简单介绍
- UISearchController和谓词
- Android Studio中进行单元测试和UI测试
- UIView详解
- 欢迎使用CSDN-markdown编辑器
- quip共同合作
- 【转】WPF MultiBinding 和 IMultiValueConverter
- iOS开发-UIImageView高效设置Radius
- [easyui]封装一个form