[LeetCode]N-Queens II
来源:互联网 发布:js判断滚动条是否滚动 编辑:程序博客网 时间:2024/05/17 07:01
本题为非常典型的回溯问题,回溯问题的实质是从初始位置出发,层层推进问题,如果遇到到达某一位置时该位置不满足题设条件,则退回到上一层,在上一层中选择下一个位置继续进行试探。回溯问题相当于相对于枚举法进行了剪枝处理,一定程度上提高了效率。
这道题我完全没有做出来,全部是通过别人的答案进行拼凑,但中间还是出现了问题。代码如下:
public class Solution { public int count = 0;public int totalNQueens(int n) { int[] res=new int[n+1]; for(int i=0;i<n;i++){ res[i]=-100; } countRow(0,res,n); return count; } private void countRow(int n,int[] res,int total){ if(n==total)count++; for(int i=0;i<total;i++){ boolean isqueen=true; for(int j=0;j<total;j++){ if(!isQueen(n,i,j,res[j])){ isqueen=false; break; } } if(isqueen){ res[n]=i; countRow(n+1,res,total); res[n]=-100; } } } private boolean isQueen(int cRow,int cCol,int pRow,int pCol){ if(cCol==pCol||Math.abs(cRow-pRow)==Math.abs(cCol-pCol)){ return false; }else{ return true; } }}
问题主要出现在:1、res数组要初始化,否则初始值为0会影响到isQueen的判断;2、进行递归时选择countRow(n+1,res,total),而不是n++或者++n,因为之后递归完成返回后还要使用n进行下一位置的递归;3、isQueen里面cRow==pRow不是判断条件,因为没有相等行的存在。
上述代码还有点头重脚轻,再优化后如下:
public static int count = 0;public static int totalNQueens(int n) { int[] res=new int[n]; for(int i=0;i<n;i++){ res[i]=-100; } countRow(0,res,n); return count; } private static void countRow(int n,int[] res,int total){ if(n==total)count++; for(int i=0;i<total;i++){ if(isQueen(n,i,res)){ res[n]=i; countRow(n+1,res,total); res[n]=-100; } } } private static boolean isQueen(int cRow,int cCol,int[] res){ for(int i=0;i<res.length;i++){ if(cCol==res[i]||Math.abs(cRow-i)==Math.abs(cCol-res[i])){ return false; } } return true; }
回溯法之后还要反复练习。
0 0
- LeetCode: N-Queens II
- LeetCode : N-Queens II
- [Leetcode] N-Queens II
- 【leetcode】N-Queens II
- LeetCode: N Queens II
- [LeetCode]N-Queens II
- LeetCode - N-Queens II
- LeetCode:N-Queens II
- 【leetcode】N-Queens II
- LeetCode:N-Queens II
- Leetcode: N-Queens II
- leetcode N-Queens II
- LeetCode | N-Queens II
- Leetcode: N-Queens II
- LeetCode N-Queens II
- Leetcode N-Queens II
- N-Queens II -- LeetCode
- N-Queens II - LeetCode
- setPassword3的问题
- eclipse Generating Getters and Setters Failed
- openwrt手动恢复出厂设置
- go-redis in golang
- Android Studio中使用AIDL以及couldn't find import for class问题的处理
- [LeetCode]N-Queens II
- Java中字符串探索—-String ,StringBuffer ,StringBuilder及字符串缓存池
- UIWebView 的使用
- 堆和栈的区别(转过无数次的文章)
- iOS进阶路线以及进阶书籍
- Android 教你打造炫酷的ViewPagerIndicator 不仅仅是高仿MIUI
- 第十一届湖南省省赛 - Internet of Lights and Switches(二分 + 位运算)
- PHP Cache缓存机制与文件缓存原理
- python安装MySQLdb