private static int nn=5,m =4, p=4, q=3, min = 99999999;
private static int[,] aa = new int[51, 51];
private static int[,] book1 = new int[51, 51];
private static void Main(string[] args)
{
int i, j, startx, starty;
// int n = Convert.ToInt32(Console.ReadLine());
// int m = Convert.ToInt32(Console.ReadLine());
aa[1, 1] = 0;
aa[1, 2] = 0;
aa[1, 3] = 1;
aa[1, 4] = 0;
aa[2, 1] = 0;
aa[2, 2] = 0;
aa[2, 3] = 0;
aa[2, 4] = 0;
aa[3, 1] = 0;
aa[3, 2] = 0;
aa[3, 3] = 1;
aa[3, 4] = 0;
aa[4, 1] = 0;
aa[4, 2] = 1;
aa[4, 3] = 0;
aa[4, 4] = 0;
aa[5, 1] = 0;
aa[5, 2] = 0;
aa[5, 3] = 0;
aa[5, 4] = 1;
for ( i = 1; i <= 5; i++)
{
for ( j = 1; j <= 4; j++)
{
Console.Write(aa[i,j]);
}
Console.WriteLine();
}
book1[1, 1] = 1;
dfs(1,1,0);
Console.WriteLine("最小步骤:{0}",min);
Console.ReadKey();
}
#region 深度算法之迷宫
public static void dfs(int x, int y, int step)
{
int[,] next = new int[4, 2]{
{0,1},
{1,0},
{0,-1},
{-1,0}};
int tx, ty, k;
if (x == p && y == q)
{
if (step < min)
{
min = step;
}
return;
}
for (k = 0; k <= 3; k++)
{
tx = x + next[k, 0];
ty = y + next[k, 1];
if (tx < 1 || ty < 1 || tx > nn || ty > m)
{
continue;
}
if (aa[tx, ty] == 0 && book1[tx, ty] == 0)
{
book1[tx, ty] = 1;
dfs(tx, ty, step + 1);
book1[tx, ty] = 0;
}
}
}
#endregion 深度算法之迷宫
文章转之:《啊哈!算法》