0
這裏是使用++ DFS在C,它有缺陷,拓撲排序(出界錯誤)拓撲使用排序DFS
#include<iostream>
#include<stdio.h>
using namespace std;
int count=0;
static int *a=new int[8];
void dfs(int u,bool v[],bool matrix[][8])
{
v[u]=true;
for(int i=0;i<8;i++)
if(!v[i]&& matrix[u][i])
dfs(i,v,matrix);
a[count++]=u;
}
int main()
{
bool v[8];
bool matrix[8][8];
matrix[7][6]=true;
matrix[0][1];
matrix[1][2]=true;
matrix[2][3]=true;
matrix[3][4]=true;
matrix[2][5]=true;
for(int i=0;i<8;i++)
if(!v[i])
dfs(i,v,matrix);
for(int i=0;i<8;i++)
cout<<a[7-i]<<" ";
}
請幫我解決這個錯誤,我想我應該建立矩陣[8] [ 2],但之後如何繼續?
下面是超出範圍訪問'a [count ++] = u;'的一個候選人。你怎麼知道在遞歸調用期間'count'總是*在範圍內? – 2012-04-28 11:05:27
您遇到什麼錯誤?它與'v'和'matrix'中的許多元素是否未初始化有關? – Attila 2012-04-28 11:05:55
@BoPersson - 調用'dfs'的條件是'v [i]'是'false'。 'v'中只有8個元素,而'dfs'中當前的元素被設置爲'false',所以我不認爲會因爲遞歸而導致過度索引。 – Attila 2012-04-28 11:07:38