N-Queens
来源:互联网 发布:linux 怎么搭建lamp 编辑:程序博客网 时间:2024/05/22 03:53
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<String[]> solveNQueens(int n) { ArrayList<String[]> result=new ArrayList<String[]>(); Integer []columns=new Integer[n]; placeQueens(0,n,columns,result); return result; } //dfs public void placeQueens(int row,int n,Integer[] columns,ArrayList<String[]> result){ if(row==n){ String[] arr=new String[n]; for(int i=0;i<n;i++){ StringBuffer sb=new StringBuffer(); for(int j=0;j<n;j++){ if(columns[i]==j) sb.append("Q"); else sb.append("."); } arr[i]=sb.toString(); } result.add(arr); } else { for(int col=0;col<n;col++){ if(isValid(columns,row,col)){ columns[row]=col; placeQueens(row+1,n,columns,result); } } } } public boolean isValid(Integer[] columns,int row1,int column1){ for(int row2=0;row2<row1;row2++){ int column2=columns[row2]; //check column if(column1==column2) return false; //check duijiaoxian int colDistance=Math.abs(column1-column2); int rowDistance=row1-row2; if(colDistance==rowDistance) return false; } return true; }}
0 0
- N-Queens
- N-Queens
- N-Queens
- N-Queens
- N-Queens
- N-Queens
- N-Queens
- N-Queens
- N-Queens
- N-Queens
- N-Queens
- N-queens
- N-Queens
- N-Queens
- N-Queens
- N-Queens
- N-Queens
- N-Queens
- Java基础概述
- linux 文件其他权限(s、t、i、a)解析
- 批处理写的关机程序
- 自定义标签的学习
- mac os x 使用scp代替sz rz
- N-Queens
- 常用js正则表达式
- POJ 2533 Longest Ordered Subsequence (最长上升子序列 DP优化)
- .net对象二进制序列化
- Python 查找含有或者不含有特定字符的字符
- Unicode和中文互转
- .net FileUpload控件在选择文件后上传文件时 始终出现找不到文件的问题
- 有关xcode
- iOS程序完成后如何生成ipa进行真机测试