자료구조, 알고리즘 문제 풀이/자료구조
인접행렬 구현
재우이
2022. 2. 17. 02:52
총 코드
#include<iostream>
using namespace std;
#define MAX 256
class AdjMatrixGraph
{
private:
int size;
char vertex[MAX];
int edge[MAX][MAX];
public:
AdjMatrixGraph() {};
~AdjMatrixGraph() {};
void Init();
char GetVertex(int i) { return vertex[i]; }
void SetVertex(char ch) { vertex[size++] = ch; }
int GetEdge(int i, int j) { return edge[i][j]; }
void SetEdge(int i, int j, int val) { edge[i][j] = val; }
void InsertVertex(char name);
void InsertEdge(int u, int v);
void Display();
};
void AdjMatrixGraph::Init()
{
size = 0;
for (auto i = 0; i < MAX; i++)
{
for (auto j = 0; j < MAX; j++)
{
SetEdge(i, j, 0);
}
}
}
void AdjMatrixGraph::InsertVertex(char name)
{
if (size > MAX)
{
cout << "Graph Vertex FULL ERROR" << endl;
return;
}
SetVertex(name);
}
void AdjMatrixGraph::InsertEdge(int u, int v)
{
SetEdge(u, v, 1);
SetEdge(v, u, 1);
}
void AdjMatrixGraph::Display()
{
cout << "Vertex size : " << size << endl << endl;
cout << " ";
for (auto i = 0; i < size; i++)
{
cout << vertex[i] << " ";
}
cout << endl;
for(auto i = 0; i < size; i++)
{
cout << vertex[i] << ":";
for (auto j = 0; j < size; j++)
{
cout << GetEdge(i,j) << " ";
}
cout << endl;
}
}
int main()
{
AdjMatrixGraph graph;
graph.Init();
graph.InsertVertex('A');
graph.InsertVertex('B');
graph.InsertVertex('C');
graph.InsertVertex('D');
graph.InsertEdge(0, 1);
graph.InsertEdge(0, 2);
graph.InsertEdge(1, 2);
graph.InsertEdge(1, 3);
graph.InsertEdge(2, 3);
graph.Display();
}