日期:2014-05-17 浏览次数:21055 次
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); } } } } }