# Depth First Traversal

Depth first traversal, also known as depth first search or DFS, is an algorithm for traversing or searching tree or graph data structures. One starts at the root (selecting some arbitrary node as the root in the case of a graph) and explores as far as possible along each branch before backtracking.

```									```/*****Please include following header files*****/
// stdio.h
/***********************************************/

typedef struct vertex_struct {
char Label;
bool Visited;
} Vertex;

int _top = -1;
int _vertexCount = 0;

void Push(int* stack, int item) {
stack[++_top] = item;
}

int Pop(int* stack) {
return stack[_top--];
}

int Peek(int* stack) {
return stack[_top];
}

bool IsStackEmpty() {
return _top == -1;
}

int** Create2DArray(int rowCount, int colCount) {
int** arr = new int*[rowCount];

for (int i = 0; i < rowCount; ++i)
arr[i] = new int[colCount];

return arr;
}

void AddVertex(Vertex** arrVertices, char label) {
Vertex* vertex = new Vertex();
vertex->Label = label;
vertex->Visited = false;
arrVertices[_vertexCount++] = vertex;
}

}

void DisplayVertex(Vertex** arrVertices, int vertexIndex) {
printf("%c ", arrVertices[vertexIndex]->Label);
}

for (int i = 0; i < _vertexCount; ++i) {
if (adjacencyMatrix[vertexIndex][i] == 1 && arrVertices[i]->Visited == false) {
return i;
}
}
return -1;
}

void DepthFirstSearch(Vertex** arrVertices, int** adjacencyMatrix, int* stack) {
arrVertices->Visited = true;
DisplayVertex(arrVertices, 0);
Push(stack, 0);

while (!IsStackEmpty()) {

if (unvisitedVertex == -1) {
Pop(stack);
}
else {
arrVertices[unvisitedVertex]->Visited = true;
DisplayVertex(arrVertices, unvisitedVertex);
Push(stack, unvisitedVertex);
}
}

for (int i = 0; i < _vertexCount; ++i) {
arrVertices[i]->Visited = false;
}
}```
```

### Example

```									```int max = 5;
int* stack = new int[max];
Vertex** arrVertices = new Vertex*[max];

for (int i = 0; i < max; ++i)
for (int j = 0; j < max; ++j)

```									`Depth First Search: S A D B C`