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-22 13:51:12 -07:00

3.6 KiB

id title author prerequisites description
dfs Depth First Search Siyong Huang
Bronze - Introduction to Graphs
A way to traverse a graph using recursion.

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