(转)五大常用算法之四:回溯法
2015-05-13 17:17
113 查看
http://www.cnblogs.com/steven_oyj/archive/2010/05/22/1741376.html
[/code]
[/code]
(3)递归的算法框架
回溯法是对解空间的深度优先搜索,在一般情况下使用递归函数来实现回溯法比较简单,其中i为搜索的深度,框架如下:
[/code]
[/code]
N皇后问题代码:
View Code
分类: 经典算法
[code]
[/code]
[/code]
(3)递归的算法框架
回溯法是对解空间的深度优先搜索,在一般情况下使用递归函数来实现回溯法比较简单,其中i为搜索的深度,框架如下:
[code][code]
[/code]
[/code]
N皇后问题代码:
public class N_QueueProblem { bool isSafe(int[] columns, int rowIndex) // columns[rowIndex] { int i; for (i = 1; i < rowIndex; i++) { int Column_diff = Math.Abs(columns[rowIndex] - columns[i]); int Row_diff = Math.Abs(rowIndex - i); if (columns[i] == columns[rowIndex] || Column_diff == Row_diff) return false; } return true; } public List<int[]> Solve(int n) { int[] columns = new int[n + 1]; int index = 1; List<int[]> goodresult = new List<int[]>(); for (int i = 1; i <= n; i++) columns[i] = 0; while (index > 0) { columns[index]++;//试一试index 行,columns[index]列 while (columns[index] <= n && !isSafe(columns, index)) columns[index]++; if (columns[index] <= n) { if (index == n) { int[] array = new int[columns.Length]; Array.Copy(columns, array, columns.Length); goodresult.Add(array); //让最后一行的列数超过n,被迫index-- columns[index] = columns[index]+n+1; } else { index++; //初始化 columns[index] = 0; } } else index--; } return goodresult; } }
View Code
分类: 经典算法
相关文章推荐
- 五大常用算法:分治、动态规划、贪心、回溯和分支界定
- 五大常用算法之四:回溯法
- 五大常用算法之四:回溯法
- 五大常用算法:分治、动态规划、贪心、回溯、分支限界
- 五大常用算法:分治法,动态规划,贪心,回溯,分支限界法
- 五大常用算法之四:回溯法
- 五大常用算法之四:回溯法
- 五大常用算法之四:回溯法
- 五大常用算法——分治法,动态规划,回溯法,分支界限法,贪心算法
- 五大常用算法:分治、动态规划、贪心、回溯和分支界定
- [转]五大常用算法:分治、动态规划、贪心、回溯和分支界定
- 五大常用算法之四:回溯算法
- 【转载】五大常用算法之四:回溯法
- 五大常用算法——分治法,动态规划,回溯法,分支界限法,贪心算法
- 五大常用算法——分治法,动态规划,回溯法,分支界限法,贪心算法
- 五大常用算法——分治法,动态规划,回溯法,分支界限法,贪心算法
- 五大常用算法——分治法,动态规划,回溯法,分支界限法,贪心算法
- 五大常用算法:分治、动态规划、贪心、回溯和分支界定
- 五大常用算法之四:回溯法
- 五大常用算法之四:回溯法