This repository has been archived on 2022-06-22. You can view files and clone it, but cannot push or open issues or pull requests.
usaco-guide/content/4_Silver/DFS.md
2020-06-16 13:09:59 -04:00

4.9 KiB

id title author prerequisites
dfs Depth First Search Siyong Huang
Bronze - Introduction to Graphs
  • Depth First Search (DFS)
  • Flood Fill
  • Graph Two-Coloring

Depth First Search (DFS)

Depth First Search, more commonly DFS, is a fundamental graph algorithm that traverses an entire connected component. The rest of this document describes various applications of DFS. Of course, it is one possible way to implement flood fill. Breadth first search (BFS) is not required for silver.

Tutorial

Problems

Flood Fill

Flood Fill refers to finding the number of connected components in a graph, usually when the graph is a grid.

Tutorial

Problems

Graph Two-Coloring

Graph two-coloring refers to assigning a boolean value to each node of the graph, dictated by the edge configuration The most common example of a two-colored graph is a bipartite graph, in which each edge connects two nodes of opposite colors.

Tutorial

The idea is that we can arbitrarily label a node and then run DFS. Every time we visit a new (unvisited) node, we set its color based on the edge rule. When we visit a previously visited node, check to see whether its color matches the edge rule. For example, an implementation of coloring a bipartite graph is shown below.

//UNTESTED

bool is_bipartite = true;
void dfs(int node)
{
	visited[node] = true;
	for(int u:adj_list[node])
		if(visited[u])
		{
			if(color[u] == color[node])
				is_bipartite = false;
		}
		else
		{
			color[u] = !color[node];
			dfs(u);
		}
}

Problems