您的位置:首页 > 其它

(转)五大常用算法之四:回溯法

2015-05-13 17:17 113 查看
http://www.cnblogs.com/steven_oyj/archive/2010/05/22/1741376.html

[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

分类: 经典算法
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: