here is topological sorting using DFS in c++,which has bugs(out of bound error)
#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]<<" ";
}
please help me to fix this error,i think i should create matrix[8][2],but how to continue after that?
a[count++]=u;. How do you know thatcountis always in range during the recursive calls?vandmatrixare uninitialized?dfsis thatv[i]isfalse. There are only 8 elements invand the current one is set tofalseimmediately indfs, so I don't think there will be overindexing due to recursion.