vector<vector<int>> adjancent; vector<bool> visited; void CreateGraph() { adjancent = vector<vector<int>>(6); adjancent[0] = { 1,3 }; adjancent[1] = { 0,2,3 }; adjancent[3] = { 4 }; adjancent[5] = { 4 }; visited = vector<bool>(6, false); } void DFS(int here) { if (visited[here] == true) return; cout << here << " 방문 " << endl; visited[here] = true; for (int i = 0; i < adjancent[here].size(); i++) { DFS(adjancent[here][i]); } } int main() { CreateGraph(); DFS(0); }
방문한 노드를 닫아주는 vector<bool> visited; 변수
각 연결 간선 adjancent;
DFS를 재귀적으로 돌면서 방문한 노드는 return을
아니라면 방문했다고 알려주고
연결된 간선만큼 DFS를 돌아준다.