# Graph

Shown above is a simple graph. Let’s define the characteristic of the graph:

• This is a connected graph. Meaning, you can travel from anywhere to anywhere in this graph.  Read further here
• This is an undirected graph. That simply means we don’t have any direction sense to the arrow connecting two nodes
• This is an unweighted graph which is a different way of saying all the edges carry equal weight

An adjacency list is a collection of unordered lists used to represent a finite graph. Each list describes the set of neighbors of a vertex in the graph. Read the wiki page here.

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.

 graph = {'A' : set(['G','B']), 'B' : set(['C','D','A']), 'C' : set(['F','D','B']), 'D' : set(['B','C']), 'E' : set(['F']), 'F' : set(['E','C']), 'G' : set(['A']), } print graph ##Output should be {'A': set(['B', 'G']), 'C': set(['B', 'D', 'F']), ## 'B': set(['A', 'C', 'D']), 'E': set(['F']), 'D': set(['C', 'B']), ## 'G': set(['A']), 'F': set(['C', 'E'])}

view raw

graph_dict.py

hosted with ❤ by GitHub

Our graph is now being represented in python dictionary using set

## Print Nodes of Graph

We will now transverse the graph in depth-first fashion and try to print all the elements of the graph. Let’s say we start from A, we explore all the immediate neighbors before backtracking and then turn back when there is no further nodes.

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.