我已經對什麼是有向圖和無向圖進行了研究。我的方法是使用DFS算法。我知道當visitedM[iVertices]
是true
或節點被訪問兩次,這意味着它不是一棵樹。我還確定一個圖是否是一棵樹,我使用下面的定理。確定一個無向圖是否是樹
Theorem: Any connected graph with n vertices and n-1 edges is a tree
我的代碼是由從文件中讀取邊緣的頂點的數量和數量如下
6 7
1 2
1 5
1 6
2 5
正如你可以看到每個邊緣上列出與源頂點和目標頂點一行初始化。頂點從1開始。邊緣是無向的,一旦從最小的頂點ID開始,將在文件上列出 。例如,對於邊緣2-5和5-2,文件只有2-5。
我的問題是,我不知道如果我應該分配節點內存,如何將節點插入圖中,我如何告訴我從DFS代碼不是一棵樹。我還將void dfs
作爲int函數返回訪問頂點的數量。 int dft(grapg *g, int iV, int VisitedM[])
。該函數與我的void DFS
類似,但如果visitedM[iV]
,visitedM[iV] = TRUE
返回0 ,並且返回iCount
。 我也假設我的數據結構很混亂。
#define MAX_VERTICES 100
typedef struct EdgeNode
{
int y;
int w; //weight
int iVertex //susbcript in vertexM for TO Vertex
struct EdgeNode *pNextEdge;
}EdgeNode;
typedef struct Vertex
{
char szLabel[100 +1 ];
EdgeNode *successorList;
}Vertex;
typedef struct
{
int iNumVertices;
int iNumEdges;
int iDirected;
Vertex vertexM[MAX_VERTICES +1];
int iParent[MAX_VERTICES + 1];
int iVisitedM[MAX_VERTICES + 1];
int degree[MAX_VERTICES + 1];
EdgeNode *edge[MAX_VERTICES +1];
}GraphImp;
typedef GraphImp *Graph;
int main(int argc, char *argv[])
{
FILE *pFile;
Graph graph;
char szInputBuffer[100];
int numEdges, numVertices;
pFile = fopen("a.txt","r");
if(pFile == NULL)
{
printf("FILE DOES NOT EXIST \n");
return;
}
//reads file until EOF
while(fscanf(pFile, "%d%d", &graph.iVertices, &graph.iEdges) != EOF)
{
//printf is to track the input from file
printf("num of vertices: %d \n num of edeges: %d \n",graph.iVertices, graph.iEdges);
}
fclose(pFile);
}
void dft(Graph *g, int iV, int visitedM[])
{
EdgeNode *e;
if(visitedM[iV])
return;
for(e = g->vertexM[iV].sucessorList; e!= NULL; e = e->pNextEdge)
{
dft(g, e->iVertex, visitedM);
}
}
我明白你的方法。但是,在鄰接列表或鄰接矩陣之間實現此算法會更好嗎? –
@EduardoJuarez都不是。每條邊只需要一次。所以代碼可以從文件中讀取邊緣,更新顏色信息並放棄邊緣。沒有必要存儲邊緣。 – user3386109
我需要分配內存嗎? –