用C++改的最短路径算法
- C# code
using System;using System.Collections.Generic;using System.Text;namespace ConsoleApplication2{ public struct Postion { public int X; public int Y; public Postion(int X, int Y) { this.X = X; this.Y = Y; } }; class Program { static int[,] maze = new int[10, 10] {{ 0, 0, 0, 0,-1, 0, 0, 0, 0, 0}, { 0,-1,-1, 0, 0, 0, 0,-1, 0, 0}, { 0, 0,-1, 0,-1, 0, 0,-1, 0,-1}, { 0, 0,-1, 0,-1, 0, 0,-1, 0,-1}, { 0, 0, 0, 0,-1,-1, 0,-1, 0, 0}, { 0, 0,-1, 0, 0, 0, 0, 0, 0, 0}, { 0,-1, 0, 0,-1, 0,-1,-1, 0, 0}, { 0, 0, 0,-1, 0, 0, 0,-1, 0,-1}, {-1, 0, 0,-1, 0, 0, 0,-1, 0,-1}, { 0, 0, 0, 0, 0, 0, 0, 0, 0,-1} }; static void printPath(Stack<Postion> path)//打印路径没用的 { /* while (!path.empty()) { printf("[%d][%d] ==>> [%2d]\n", path.top().X, path.top().Y, maze[path.top().X][path.top().Y]-1); path.pop(); }*/ System.Console.Write(path.Count); } /* static void printMat(int mat[10,10])//打印地图没用的 { for (int i = 0; i < 10 ; i++) { for (int j = 0; j < 10 ; j++) { printf("%2d ", mat[i][j]); } printf("\n"); } } */ //开始用用的 static bool isCanGo(int prePosValue, int posX, int posY) { if (posX < 0 }
不知道为什么stackpath 总为空,对C# 一点都不会,可是要用到最短路径的算法。用C++的算法改了一个但是不明白这个问题是怎么产生的!!希望给我给答案,方便给个弄好的代码也行。先谢谢啦
[解决办法]
其实就差一点点就对了!
你把
if (path.Count< stackpath.Count || stackpath.Count == 0) // 更短的路径
stackpath = path;
return;
换成
- C# code
if (path.Count< stackpath.Count || stackpath.Count == 0) // 更短的路径 stackpath = new Stack<Postion>(path);return;