그래프(Graph)는 정점(Vertex) 과 간선(Edge) 으로 구성된 비선형 자료구조로, 현실 세계의 다양한 '연결 관계'를 표현하는 데 사용됩니다.
void CreateGraph_1()
{
struct Vertex
{
vector<Vertex*> edges; // 연결된 정점 목록 (포인터)
};
vector<Vertex> v(6); // 정점 6개 생성
// 간선 연결
v[0].edges.push_back(&v[1]);
v[0].edges.push_back(&v[3]);
v[1].edges.push_back(&v[0]);
v[1].edges.push_back(&v[2]);
v[1].edges.push_back(&v[3]);
v[3].edges.push_back(&v[4]);
v[5].edges.push_back(&v[4]);
// 연결 여부 확인: 0번 → 3번
bool connected = false;
for (Vertex* edge : v[0].edges)
{
if (edge == &v[3])
{
connected = true;
break;
}
}
}
void CreateGraph_2()
{
vector<vector<int>> adjacent(6); // 연결 목록
adjacent[0] = { 1, 3 };
adjacent[1] = { 0, 2, 3 };
adjacent[3] = { 4 };
adjacent[5] = { 4 };
// 연결 여부 확인
bool connected = false;
for (int vertex : adjacent[0])
{
if (vertex == 3)
{
connected = true;
break;
}
}
// STL 활용
vector<int>& adj = adjacent[0];
bool connected2 = (find(adj.begin(), adj.end(), 3) != adj.end());
}
void CreateGraph_3()
{
vector<vector<bool>> adjacent(6, vector<bool>(6, false));
adjacent[0][1] = true;
adjacent[0][3] = true;
adjacent[1][0] = true;
adjacent[1][2] = true;
adjacent[1][3] = true;
adjacent[3][4] = true;
adjacent[5][4] = true;
// 연결 여부 확인
bool connected = adjacent[0][3];
}
[from][to]로 직접 연결 여부를 확인O(1))O(N^2))vector<vector<int>> weightGraph =
{
{ -1, 15, -1, 35, -1, -1 },
{ 15, -1, 5, 10, -1, -1 },
{ -1, -1, -1, -1, -1, -1 },
{ -1, -1, -1, -1, 5, -1 },
{ -1, -1, -1, -1, -1, -1 },
{ -1, -1, -1, -1, 5, -1 },
};
예:
weightGraph[0][1] == 15→ 0번 정점에서 1번 정점까지의 비용은 15