#include "Graph.h"
Graph::Graph(int m_Capacity)
{
this->m_Capacity = m_Capacity;
this->m_NodeCnt = 0;
this->m_pMatrix = new int[m_Capacity*m_Capacity];
memset(m_pMatrix, 0, sizeof(int)*m_Capacity*m_Capacity);
this->m_pNodeArray = new Node[m_Capacity];
}
Graph::~Graph()
{
this->m_Capacity = 0;
this->m_NodeCnt = 0;
delete[]m_pMatrix;
m_pMatrix = NULL;
delete[]m_pNodeArray;
m_pNodeArray = NULL;
}
void Graph::AddNode(const Node & m_Node)
{
m_pNodeArray[m_NodeCnt] = m_Node;
m_NodeCnt++;
}
void Graph::reset()
{
for (auto i=0;i<m_Capacity;i++)
{
m_pNodeArray[i].SetIsVisited(false);
}
}
void Graph::SetEdgeUndirectedGraph(const Node & m_NodeA, const Node & m_NodeB, int m_Weight)
{
m_pMatrix[m_NodeA.GetIndex()*m_Capacity+ m_NodeB.GetIndex()] = m_Weight;
m_pMatrix[m_NodeB.GetIndex()*m_Capacity + m_NodeA.GetIndex()] = m_Weight;
}
void Graph::PrintMatrix()
{
for (auto i = 0; i < m_Capacity; i++)
{
for (auto j = 0; j < m_Capacity; j++)
{
cout << m_pMatrix[i*m_Capacity + j] << " ";
}
cout << endl;
}
}
int Graph::GetWeightFromMatrix(int m_row, int m_vol)
{
return m_pMatrix[m_row*m_Capacity+m_vol];
}
void Graph::DFS(int m_Index)
{
cout << m_Index << " ";
m_pNodeArray[m_Index].SetIsVisited(true);
for (auto i=0;i<m_Capacity;i++)
{
if (GetWeightFromMatrix(m_Index,i)!=0&&(!m_pNodeArray[i].GetIsVisited()))
{
DFS(i);
}
}
}
void Graph::BFS(int m_Index)
{
cout << m_Index << " ";
m_pNodeArray[m_Index].SetIsVisited(true);
vector<int>m_vec;
m_vec.push_back(m_Index);
BFS1(m_vec);
}
void Graph::BFS1(vector<int> m_vec)
{
vector<int>m_curvec;
for (auto i=0;i<m_vec.size();i++)
{
for (auto j=0;j<m_Capacity;j++)
{
if (GetWeightFromMatrix(m_vec[i],j)!=0&&!m_pNodeArray[j].GetIsVisited())
{
cout << j << " ";
m_pNodeArray[j].SetIsVisited(true);
m_curvec.push_back(j);
}
}
}
if (m_curvec.size()!=0)
{
BFS1(m_curvec);
}
else
{
return;
}
}