1. 程式人生 > >有向圖的鄰接矩陣

有向圖的鄰接矩陣

所謂用鄰接矩陣,是用一個二維陣列儲存,邊使用矩陣來構建模型,這使得每一個頂點和其它頂點之間都有邊的有無 的 表示的機會。若有邊,則他們交點 為1 ,否則為0。當然,如果是一副邊有權值的圖,交點儲存的是他們邊的權值。
有1必有回1則為無向圖,有1未必有回1則為有向圖

const int MAX_VERTEX = 3;//資料的數量

struct ArrayGraph
{
    vector<string>vertexArr;//頂點元素陣列
    int arcArr[MAX_VERTEX][MAX_VERTEX];//連結弧二維陣列
};

void ArrayGraph_init(ArrayGraph &pGraph);
void
ArrayGraph_create(ArrayGraph &pGraph); void ArrayGraph_show(ArrayGraph &pGraph); int main() { ArrayGraph graph; ArrayGraph_init(graph); ArrayGraph_create(graph); ArrayGraph_show(graph); system("pause"); return 0; } void ArrayGraph_init(ArrayGraph & pGraph) { for
(int i = 0; i < MAX_VERTEX; ++i) { pGraph.arcArr[i][i] = 0; } } void ArrayGraph_create(ArrayGraph & pGraph) { for (int i = 0; i < MAX_VERTEX; ++i) { cout << "請輸入第" << i + 1 << "個頂點值" << endl; string strMsg; cin >> strMsg; pGraph.vertexArr.push_back(strMsg); } for
(int i = 0; i < MAX_VERTEX; ++i) { for (int j = i + 1; j < MAX_VERTEX; ++j) { cout << "若元素" << pGraph.vertexArr[i] << "有指向" << pGraph.vertexArr[j] << "的弧,則輸入1,否則輸入0" << endl; int IntMsg; cin >> IntMsg; pGraph.arcArr[i][j] = IntMsg; cout << "若元素" << pGraph.vertexArr[j] << "有指向" << pGraph.vertexArr[i] << "的弧,則輸入1,否則輸入0" << endl; cin >> IntMsg; pGraph.arcArr[j][i] = IntMsg; } } } void ArrayGraph_show(ArrayGraph & pGraph) { cout << "頂點元素如下" << endl; for (int i = 0; i < MAX_VERTEX; ++i) { cout << pGraph.vertexArr[i] << " "; } cout << endl << endl; cout << "矩陣如下" << endl << endl << " "; for (int i = 0; i < MAX_VERTEX; ++i) { cout << pGraph.vertexArr[i] << " "; } cout << endl; for (int i = 0; i < MAX_VERTEX; ++i) { cout << pGraph.vertexArr[i] << " "; for (int j = 0; j < MAX_VERTEX; ++j) { cout << pGraph.arcArr[i][j] << " "; } cout << endl; } cout << endl; }