using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SeqListSort { /// <summary> /// <ather> /// <lihonglin> /// </ather> /// <content> /// 随机生成 Row 行* Col列的迷宫,0为可以通过,1为不可以通过,若可以通过显示出路径,不能通过则显示 /// 出内容 /// </content> /// </summary> public struct Point { public int x; public int y; public Point(int x, int y) { this.x = x; this.y = y; } } class MazePath { const int ROW = 10; const int COL = 10;// //static int[,] map = new int[ROW,COL]; //测试 static int[,] map = new int[,] {{1,1,1,1,1,1,1,1,1,1}, {1,0,1,1,1,0,1,1,1,1}, {1,0,0,1,0,1,1,1,1,1}, {1,0,1,0,0,0,0,0,1,1}, {1,0,0,0,1,0,1,0,1,1}, {1,1,1,0,1,1,0,0,1,1}, {1,0,1,0,0,0,1,0,0,1}, {1,0,1,1,0,0,1,1,0,1}, {1,0,1,1,0,0,0,0,0,1}, {1,1,1,1,1,1,1,1,1,1}};//迷宫地图 static Stack<Point> path = new Stack<Point>();//迷宫路径 public static void InitMap() { Random r = new Random(); for (int i = 0; i < ROW; ++i ) { for (int j = 0; j < COL; ++j ) { if ( 1 == i && 1 == j ) { map[i, j] = 0;// 定义入口 Console.Write(" *"); } else if (i == ROW - 2 && j == COL - 2) { map[i, j] = 0;//定义出口 Console.Write(" #"); } else if ((0 == i || 0 == j) || (i == ROW - 1 || j == COL - 1)) { map[i, j] = 1;//绘制墙 Console.Write(" " + map[i, j]); } else { map[i, j] = r.Next(0, 2);// 0为可以通过,1为不可以 Console.Write(" " + map[i,j]); } } Console.WriteLine( ); } } public static void FindPaths() { int i = 1; int j = 1; path.Push(new Point(i, j)); // 从右边开始按照顺时针开始查询 while( path.Count > 0 ) { // right if (0 == map[i, j + 1]) { map[i, ++j] = 2; path.Push(new Point(i, j)); } // bottom else if (0 == map[i + 1, j] ) { map[++i, j] = 2; path.Push(new Point(i, j)); } //left else if (0 == map[i, j - 1]) { map[i, j - 1] = 2; path.Push(new Point(i, j - 1)); j--; } // top else if (0 == map[i - 1, j]) { map[i - 1, j] = 2; path.Push(new Point(i - 1, j)); i--; } else { //Point p = path.Peek(); path.Pop(); if (path.Count <= 0) { Console.WriteLine("没有路径"); break; } } i = path.Peek().x; j = path.Peek().y; if ( i == ROW - 2 && j == COL - 2) { Console.WriteLine("找到路径显示如下:"); break; } } for (i = 0; i < ROW ; ++i) { for (j = 0; j < COL ; ++j) { if (1 == i && 1 == j) { Console.Write(" *"); } else if (i == ROW - 2 && j == COL - 2) { Console.Write(" #"); } else Console.Write(" " + map[i,j]); } Console.WriteLine( ); } } } }