DFS

void dfs(int v) {
	nodePointer w;
	if(!visited[v]) {
		visited[v] = TRUE;
		printf("%5d", v);
		for(w = graph[v]; w; w = w->link)
			dfs(w->vertex);
	}
}

iterative implementation

void dfs(int v) {
	nodePointer w;
	push(v);
	while(top) { /* stack is not empty */
		v = pop();
		if(!visited[v]) {
			visited[v] = TRUE;
			printf("%5d", v);
			for(w = graph[v]; w; w = w->link)
				push(w->vertex);
		}
	}
}

BFS

void bfs(int v) {
	nodePointer w;
	addq(v);
	while(front) { /* queue is not empty */
		v = deleteq();
		if(!visited[v]) {
			visited[v] = TRUE;
			printf("%5d", v);
			for(w = graph[v]; w; w = w->link)
				addq(w->vertex);
		}
	}
}

Generic graph traverse algorithm

/* the generic graph traverse algorithm */
put a vertex v into the bag
while(the bag is not empty) { /* iterates over all vertices */
	take a vertex v from the bag
	if(v is unmarked) {
		mark v
		for(each edge w adjacent to v) { /* iterates over all edges */
			put w into the bag
	}
}

Best-fit search

bag을 priority queue로 구현하면 T(n + e log n) = O(e log n)

이때 log n 은 edge를 알맞은 자리에 넣고빼는 시간

Connected Components

/* count the connected components of a graph */
void connected(void) {
	int i, count = 0;
	for(i = 0; i < n; i++)
		if(!visited[i]) {
			count = count + 1; /* the next connected component */
			countAndLabel(i, count);
		}
}

/* count and label connected components using DFS */
void countAndLabel(int v, int count) {
	nodePointer w;
	push(v);
	while(top) { /* stack is not empty */
		v = pop();
		if(!visited[v]) {
			visited[v] = TRUE;
			comp[v] = count; /* set the component number of v */
			for(w = graph[v]; w; w = w->link)
				push(w->vertex);
		}
	}
}

Spanning Trees