骑士旅行问题 C#出现堆栈溢出
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
public static int o=0;
//定义步数
public static int step = 0;
//定义走法
public static int[] a = { -2, 2, -1, 1, -2, 2, -1, 1 };
public static int[] b = { -1, -1, -2, -2, 1, 1, 2, 2 };
public static int[] dk = {0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0};
static void Main(string[] args)
{
//初始化棋盘
int[,] chess = new int[8, 8];
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
chess[i, j] = 0;
//Console.Write(chess[0, 0].ToString());
}
}
travel(3, 1, chess,0);
}
public static void travel(int i,int j,int[,] chess,int p){
o++;
// Console.WriteLine("gggg");
// Console.WriteLine(o.ToString() + i.ToString() +j.ToString() + p.ToString());
// 输出结果
if (step ==64){
for (int w = 0; w < 8; w++)
{
for (int q = 0; q < 8; q++)
{
//chess[w, q] = 0;
if (chess[w, q] < 10) {
Console.Write("0");
}
Console.Write(chess[w, q].ToString());
Console.Write(" ");
}
Console.WriteLine();
}
//Console.WriteLine(o.ToString()+" "+i.ToString()+" "+j.ToString()+" "+p.ToString());
Console.ReadLine();
}
int l;
//对八种走法进行循环
for ( l = p; l < 8; l++) {
if (((i + a[l]) >= 0) && ((i + a[l]) <= 7)&&((j + b[l]) >= 0) && ((j + b[l]) <= 7)&&(chess[i + a[l], j + b[l]]) == 0)
{
// Console.WriteLine("gggg");
step++;
dk[step] = l;
chess[i + a[l], j + b[l]] = step;
travel(i + a[l], j + b[l],chess,0);
return;
}
// Console.WriteLine("gggg");
}
//如果循环结束也没有路可以走,则回到上一步
if (l == 8)
{
//Console.WriteLine("gggg");
//dk[step] = 7;
step--;
chess[i , j] = 0;
for (int w = 0; w < 8; w++)
{
for (int q = 0; q < 8; q++)
{
if (chess[w, q] == step) {
travel(w,q,chess,dk[step+1]+1);
dk[step] = 0;
return;
}
}
}
}
}
}
}
上面是我的代码,当将step设置为61进行输出时,能正常输出结果,在向上就出现堆栈溢出的问题了,求帮忙 c#
string
[解决办法]
你的递归很奇怪啊。。。
输出的一段没有问题,后面我觉得应该改成
for ( l = p; l < 8; l++) {
if (((i + a[l]) >= 0) && ((i + a[l]) <= 7)&&((j + b[l]) >= 0) && ((j + b[l]) <= 7)&&(chess[i + a[l], j + b[l]]) == 0)
{
step++;
dk[step] = l;
chess[i + a[l], j + b[l]] = step;
travel(i + a[l], j + b[l],chess,0);
chess[i+a[l],j+b[l]]=0;step--;
}
既然是递归了为什么还有走完8个方向退回,递归自动就回到上一层了。