我有这个函数可以创建一个 BFS 。我有一个功能,这是我的代码,并且:
static void Breadth_first_search(Queue<int> Q, List<int > trace, int[,] grid, int start, int nodes)
{
int u;
List<int> visited = new List<int>(220000);
Q.Enqueue(start);
trace[start] = -1;
visited[start] = 1;
do
{
u = Q.Peek();
Q.Dequeue();
for (int v = 1; v <= nodes; ++v)
{
if ((grid[u, v] == 1) && visited[v] == 0)
{
Q.Enqueue(v);
trace[v] = u;
visited[v] = 1;
}
}
} while (Q.Count != 0);
}
问题是那行不通。我有这个错误:
指数超出范围。必须是非负数且小于集合的大小。参数名称:索引
在这儿 :
trace[start] = -1;
visited[start] = 1;
我在 main 中调用了函数:
static int Main()
{
List<int> trace = new List<int>(220);
Queue<int> Q = new Queue<int>();
int[,] grid = new int[582,582];
int nodes;
int vertices;
Console.Write("Please input the number of Node : \n");
nodes = Convert.ToInt32(Console.ReadLine());
vertices = 200;
Read_input_from_user(grid, vertices);
int starting_position;
int finishing_position;
Console.Write("Please Input the Starting Node : \n");
starting_position = Convert.ToInt32(Console.ReadLine());
Console.Write("Please Input the Finishing Node : \n");
finishing_position = Convert.ToInt32(Console.ReadLine());
Breadth_first_search(Q, trace, grid, starting_position, nodes);
Trace_result(trace, starting_position, finishing_position, nodes);
Console.ReadLine();
return 0;
}