C語言實(shí)現(xiàn)圖的搜索算法示例
本文實(shí)例講述了C語言實(shí)現(xiàn)圖的搜索算法。分享給大家供大家參考,具體如下:
在游戲中,常常遇到路徑規(guī)劃問題,用到圖的相關(guān)算法,我們以簡單圖來學(xué)習(xí)。
圖通常有兩種表示方式,矩陣和鄰接表。矩陣表示簡單,運(yùn)算快,但當(dāng)矩陣是稀疏矩陣的時候就存在空間浪費(fèi)的問題,并且效率也會下降,而鄰接表節(jié)約空間,并且由于邊是連續(xù)訪問,時間效率也比較高。在本文中,我們將以鄰接表來表示圖。
#include<queue> #include<stack> using namespace std; struct SE{ int vIndex; int tag; SE* next; }; struct SMap{ SE* pE; int nnode; }; void visit(SE *se){ printf("%d\n", se->vIndex); } SMap* create_map(int matrix[][6], int n){ SMap* pMap = new SMap(); pMap->nnode = n; pMap->pE = new SE[n]; memset(pMap->pE, 0, n*sizeof(SE)); for (int i = 0; i<n; i++){ pMap->pE[i].vIndex = i; pMap->pE[i].tag = 0; SE* p = &pMap->pE[i]; for (int j = 0; j<n; j++){ if (matrix[i][j] != 0){ p->next = new SE(); p->next->vIndex = j; p->next->tag = 0; p->next->next = NULL; p = p->next; } } } return pMap; } int BFS(SMap* pMap, int n){ queue<SE*> q; for (int i = 0; i < n; i++){ if (pMap->pE[i].tag == 0){ q.push(&pMap->pE[i]); while (!q.empty()){ SE *se = q.front(); q.pop(); if (pMap->pE[se->vIndex].tag == 1){ continue; } visit(se); pMap->pE[se->vIndex].tag = 1; SE * p = se; while (p->next){ p = p->next; if (pMap->pE[p->vIndex].tag == 0){ q.push(p); } } } } } return 0; } int DFS(SMap* pMap, int n){ stack<SE*> s; for (int i = 0; i < n; i++){ if (pMap->pE[i].tag == 0){ s.push(&pMap->pE[i]); while (!s.empty()){ SE *se = s.top(); s.pop(); if (pMap->pE[se->vIndex].tag == 1){ continue; } visit(se); pMap->pE[se->vIndex].tag = 1; SE * p = &pMap->pE[se->vIndex]; stack<SE*> tmp; while (p->next){ p = p->next; if (pMap->pE[p->vIndex].tag == 0){ tmp.push(p); } } while (!tmp.empty()){ s.push(tmp.top()); tmp.pop(); } } } } return 0; } int main(){ int map[6][6] = { { 0, 1, 0, 1, 0, 0 }, { 1, 0, 1, 1, 1, 0 }, { 0, 1, 0, 1, 0, 0 }, { 1, 1, 1, 0, 1, 0 }, { 0, 1, 0, 1, 0, 1 }, { 0, 0, 0, 0, 1, 0 } }; SMap* smap = create_map(map, 6); // BFS(smap, 6); DFS(smap, 6); return 0; }
希望本文所述對大家C語言程序設(shè)計(jì)有所幫助。
相關(guān)文章
C語言 哈希查找詳解(哈希表的創(chuàng)建、處理沖突、查找等)
哈希表是一種非常重要的數(shù)據(jù)結(jié)構(gòu),并在大量的計(jì)算機(jī)科學(xué)和工程應(yīng)用中發(fā)揮重要作用,了解哈希表的原理和實(shí)現(xiàn)方式,將有助于我們更好地理解這個數(shù)據(jù)結(jié)構(gòu)及如何應(yīng)用它來解決實(shí)際問題,這篇文章主要介紹了C語言 哈希查找(哈希表的創(chuàng)建、處理沖突、查找等),需要的朋友可以參考下2024-01-01C語言實(shí)現(xiàn)刪除某一個數(shù)組值的方法
這篇文章主要給大家分享C語言數(shù)組中刪除數(shù)組中某個值的方法,既然要學(xué)習(xí)刪除數(shù)組中的元素,我們就必須得先知道數(shù)組中有哪些元素。同時還要定義一個變量,并將需要刪除的元素賦值給那個變量。下面來看看文章的詳細(xì)內(nèi)容吧2021-11-11C++實(shí)現(xiàn)PyMysql的基本功能實(shí)例詳解
這篇文章主要介紹了C++實(shí)現(xiàn)PyMysql的基本功能,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的工作或?qū)W習(xí)有一定的參考借鑒價值,需要的朋友可以參考下2020-03-03C++語言中std::array的用法小結(jié)(神器用法)
這篇文章主要介紹了C++語言中std::array的用法小結(jié),本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-11-11C++11中value category(值類別)及move semantics(移動語義)的介紹
這篇文章主要給大家介紹了C++11中value category(值類別)及move semantics(移動語義)的介紹,文中介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2018-05-05