leetCode练习(52)
2016-10-09 10:39
337 查看
题目:N-Queens II
难度:hard
问题描述:
Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
解题思路:
与
leetCode练习(51)基本一样。在此不再赘述。
具体代码如下:
public class h_52_NQueens2 {
int res=0;
public int solveNQueens(int n) {
if(n==1){
return 1;
}
char[][] board=new char
;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
board[i][j]='.';
}
}
diedai(board,0);
return res;
}
public void diedai(char[][] b,int steps){
if(steps==b.length){//所有皇后放完,将棋盘存入lists
res++;
return;
}
char[][] boardtemp=new char[b.length][b.length];
for(int ii=0;ii<b.length;ii++){
for(int jj=0;jj<b.length;jj++){
boardtemp[ii][jj]=b[ii][jj];
}
}
for(int n=0;n<b.length;n++){
if(!this.isvalidate(b, steps, n)){
continue;
}else{
boardtemp[steps]
='Q';
diedai(boardtemp,steps+1);
}
boardtemp[steps]
='.';
}
}
public boolean isvalidate(char[][] b,int x,int y){
for(int i=0;i<b.length;i++){
for(int j=0;j<b.length;j++){
if(b[i][j]=='Q'&&(x==i||y==j||(Math.abs(i-x)==Math.abs(j-y)))){
return false;
}
}
}
return true;
}
}
难度:hard
问题描述:
Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
解题思路:
与
leetCode练习(51)基本一样。在此不再赘述。
具体代码如下:
public class h_52_NQueens2 {
int res=0;
public int solveNQueens(int n) {
if(n==1){
return 1;
}
char[][] board=new char
;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
board[i][j]='.';
}
}
diedai(board,0);
return res;
}
public void diedai(char[][] b,int steps){
if(steps==b.length){//所有皇后放完,将棋盘存入lists
res++;
return;
}
char[][] boardtemp=new char[b.length][b.length];
for(int ii=0;ii<b.length;ii++){
for(int jj=0;jj<b.length;jj++){
boardtemp[ii][jj]=b[ii][jj];
}
}
for(int n=0;n<b.length;n++){
if(!this.isvalidate(b, steps, n)){
continue;
}else{
boardtemp[steps]
='Q';
diedai(boardtemp,steps+1);
}
boardtemp[steps]
='.';
}
}
public boolean isvalidate(char[][] b,int x,int y){
for(int i=0;i<b.length;i++){
for(int j=0;j<b.length;j++){
if(b[i][j]=='Q'&&(x==i||y==j||(Math.abs(i-x)==Math.abs(j-y)))){
return false;
}
}
}
return true;
}
}
相关文章推荐
- LeetCode Online Judge 题目C# 练习 - Median of Two Sorted Arrays
- LeetCode Online Judge 题目C# 练习 - Reverse Nodes in k-Group
- LeetCode 分类练习(2)—— 三向切分 partition 思想的应用
- LeetCode Online Judge 题目C# 练习 - Two Sum
- 『LeetCode』练习第二弹_算法3,4题
- Leetcode编程练习:H指数
- leetCode练习(6)
- [Leetcode 92] 52 N-Queens II
- LeetCode练习-动态规划算法(二)
- LeetCode 练习: Subset ii
- leetCode练习(11)
- leetCode练习(27)
- LeetCode编程练习 - Plus One学习心得
- LeetCode编程练习 - Longest Harmonious Subsequence学习心得
- LeetCode编程练习 - Count Primes学习心得
- 52 leetcode - Multiply Strings
- Leetcode练习- Pow(x,n)
- leetcode练习
- 【leetcode题解】[E][52]303. Range Sum Query - Immutable
- 46-52.个人练习。