首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

用C#栈,迷宫如何写

2012-10-29 
用C#栈,迷宫怎么写我把迷宫用二维数组表示的,通路时值为0,是障碍时值大于0,为1,2,3.。。。现在我想用深度优先

用C#栈,迷宫怎么写
我把迷宫用二维数组表示的,通路时值为0,是障碍时值大于0,为1,2,3.。。。现在我想用深度优先的算法,结合栈来判断给定出口入口时迷宫是否有通路。哪位大大写下代码?因为刚学的C#,所以对栈操作不熟悉,谢谢了

[解决办法]
晕。

c#是很优雅的语言,哪有那么坑爹多地代码啊!

给你写个demo,连算法带测试,也不过这一点代码而已:

C# code
using System;using System.Collections.Generic;using System.Linq;namespace ConsoleApplication1{    class Program    {        static void Main(string[] args)        {            int[,] maze ={                      {0,1,0,0,0,0,0,0,0,0},                      {0,1,1,0,0,1,1,1,0,0},                      {0,1,1,0,0,1,1,1,0,0},                      {0,1,1,0,0,1,0,0,1,0},                      {0,1,1,1,1,1,0,0,1,0},                      {0,1,1,0,0,0,1,0,1,0},                      {0,1,0,0,1,1,1,1,1,0},                      {0,1,1,1,1,0,0,1,1,0},                      {0,1,0,0,1,1,1,1,1,1},                      {0,0,0,0,0,0,0,0,0,1}};            var result = 走迷宫(maze, 0, 1, 6, 6).ToList();            Console.WriteLine("总共找到{0}条通道可以走到终点。", result.Count);            result.ForEach(r =>            {                Console.WriteLine();                foreach (var s in r)                    Console.Write("[{0},{1}] ", s.Item1, s.Item2);                Console.WriteLine();            });            Console.ReadKey();        }        private static IEnumerable<IEnumerable<Tuple<int, int>>> 走迷宫(int[,] maze, int from_x, int from_y, int to_x, int to_y)        {            if (from_x == to_x && from_y == to_y)                yield return new Tuple<int, int>[] { new Tuple<int, int>(to_x, to_y) };            else            {                maze[from_x, from_y] = 0;                for (var i = Math.Max(0, from_x - 1); i <= Math.Min(from_x + 1, maze.GetLength(0) - 1); i++)                    for (var j = Math.Max(0, from_y - 1); j <= Math.Min(from_y + 1, maze.GetLength(1) - 1); j++)                        if ((i == from_x || j == from_y) && !(i == from_x && j == from_y) && maze[i, j] == 1)                        {                            foreach (var road in 走迷宫(maze, i, j, to_x, to_y))                                yield return new Tuple<int, int>[] { new Tuple<int, int>(from_x, from_y) }.Concat(road);                        }            }        }    }} 

热点排行