CodeChef is a non-commercial competitive programming community
Login
Username (New User? Signup) Password (Forgot Password?)
Signup
Login or
Signup with
Connect
Note
  • Publicize your achievements on your Facebook Wall.
  • Challenge your friends or ask them for help.

Site Navigation

  • PRACTICE
    • Easy
    • Medium
    • Hard
    • Challenge
    • Peer
  • COMPETE
    • All Contests
    • June Long 2012
    • May Cook-Off
    • May Long 2012
  • DISCUSS
    • Forums
    • Blog
    • Wiki
    • Facebook
    • Twitter
  • COMMUNITY
    • CodeChef Meetups
    • Campus Chapters
    • Host your Contest
    • User Groups
    • CodeChef TechTalks
    • All Educational Initiatives
  • HELP
    • Frequently Asked Questions
    • FAQ for problem setters
    • Problem Setting
    • Tutorials
    • Long Contest Ranks
    • Short Contest Ranks
    • Event Calendar
  • ABOUT
    • About CodeChef
    • Team CodeChef
    • Press Room
    • CodeChef Financials
    • CodeChef Sponsorships
    • CEO's Corner
    • Contact Us
    • About Directi
Home » Wiki » Tutorial on Graph Theory - part 1

Tutorial on Graph Theory - part 1

Table of Contents 
    1. The Konigsberg Bridge Problem
    2. Basic Terms used in Graph Theory
    3. Representing Graphs
    4. Depth First Search (DFS)

Plan: Introduction to Graph Theory, Defining Basic Terms , Representing Graphs , DFS , BFS

Homer Simpson is da bomb

Graph Theory is one topic which most of us probably would not have had as part of high school Mathematics. Leonhard Euler is regarded to have started this area of Discrete Mathematics in 1736 by describing The Konigsberg Bridge Problem. Since then it has found a lot of applications in Mathematics and Computer Science. In this tutorial we will see some of the basics of Graph Theory, mainly needed for Problem Solving. If you are already familiar with some of the topics, you can safely skip those parts, as its mainly intended for beginners. If you are a beginner, then its time to learn some fascinating stuff and solve very interesting problems. So, get ready .. take a book and a pen .. postpone your other works .. as you may get late, traversing through mazes - rescuing your friends, ride a knight, board a lot of flights and many more :)

 



Following the tradition of all the Graph Theory books, lets start with knowing what The Konigsberg Bridge Problem is.

The Konigsberg Bridge Problem

The city of Konigsberg occupied two islands plus the areas on both blanks. These regions were linked by seven bridges as shown in Fig 1

[Add Image of konigsberg : Fig 1 ]

Now the problem is to find if one could start from his/her home and walk around the city in a way that would involve crossing each bridge exactly once and return to home. The graph corresponding to this problem is on the right side in Fig 1 . Now that if each bridge has to be traversed exactly once, it follows that each part of land must have even number of bridges touching it ( also called the degree of the node, which we will see shortly ), one bridge to enter into land and other to leave from it . Clearly, all the land masses here have odd number of bridges touching them. So there doesn't exist such a walk.

 

The other famous theorem is the Four color theorem. If you happened to observe any map given in an Atlas carefully, you would have seen that the different states in a country are separated by borders and not only that, they are also colored with different colors, to distinguish between any two adjacent states (which share a common border segment) . Now the question is, how many colors do we need at max, to color the regions. Well, as the name of the theorem suggests, we need at max Four colors. This is in general true for any planar structure.

Now its time to know the formal definition of a Graph and many other basic terms related to Graphs, before we see other interesting problems :D.

 


There are a lot of terms associated with graphs and its properties. Fortunately, most of these terms are derived from the casual english words and common mathematical terms, most of which we know already. Lets take a quick look at some of the basic terms and define others as we move along.

Basic Terms used in Graph Theory

Graph: An abstract mathematical structure, to model pairwise relations between discrete objects. A graph G = ( V , E ) consists of a finite set V ( set of vertices or nodes ) and a set E (set of edges ) of 2-subsets of V. Each edge is a relation ( adjacency ) between two vertices. In general, the number of vertices is denoted by n and the number of edges is denoted by m. See the following graph and identify the set of vertices and edges.

[Add Image of a simple graph : Fig 2 ]

 

The degree of a vertex v is the number if edges which contain v i.e., the number of edges that are incident on v. Note: A loop contributes 2 to the degree of the vertex it is incident on. As each edge contributes 2 to the degree of its endpoints, the sum of all degrees of vertices equals twice the number of edges.

The different drawings of a graph, stretching, shrinking, rotating etc., will not change the properties of the graph. All those transformations represent the same graph and are said to be Isomorphic to eachother.

Multiple Edges are those edges that connect the same pair of distinct vertices. A loop is an edge which connects a vertex to itself. A graph without multiple edges and without loops is called a Simple Graph. Mostly we will deal with simple graphs only.

A Walk is a list of vertices and edges ( v0 e1 v1 e2 . . . . ek vk ), such that for 1<=i<=k, the edge ei connects vi-1 and vi . A Trail is a walk with no repeated edge. A Simple Path is a walk with no repeated vertices (hence no repeated edges). A Cycle is a path in which no vertex is repeated, except the first and the last vertex, which are same. The lengthof any of these is equal to the number of edges in it.

 

Connected Components: Lets take an empty set V1 and add a vertex u to it. Keep adding the vertices which are connected to u by some path, to the set. The maximal (no more vertices can be added) set V1 is called a connected component. The vertex set V can be partitioned corresponsing to this equivalence relation 'is connected to'. For a graph G , V = V1 U V2 U V3 ... U Vk has k connected components. If G has just one component, it is said to be a connected graph.

 

If in a graph, each edge has a sense of direction associated with it, it is called a Directed Graph. Its analogous to the one-way traffic on roads. If there is a directed edge from u to v, then using that edge we can go from u to v, but not from v to u. If each edge has some weight associated with it, it is called a Weighted Graph.

[Add image for directed and weigted graphs Fig3]

[Add example for each of these terms from Fig2]


 

Now that we know what a graph is and some basic terms, lets see how to represent a graph and store it in computer memory and access it.

Representing Graphs

To represent a graph, all we need is the set of vertices, and for each vertex the neighbors of the vertex (vertices directly connected to it by an edge) and if its a weighted graph, the weight associated with each edge. There are different ways to optimally represent a graph, depending on the density of its edges. A Sparse graph has relatively less number of edges m = O(n), where as a dense graph has significantly many edges m = O(n2)

Adjacency List

In this representation, for each node in the graph we maintain the list of its neighbors. We have an array of vertices, indexed by the vertex number and for each vertex v, the corresponding array element points to a singly-linked list of neighbors of v . The following firgure shows the Adjacency list of Graphs in Fig[ ?? ]

[ Add figure(s) for adjacency list ]

Adjacency Matrix

In this representation, we construct a nxn matrix A. If there is an edge from a vertex i to vertex j , then the corresponding element of A, ai,j = 1, otherwise ai,j= 0. Note, even if the graph on 100 vertices contains only 1 edge, we still have to have a 100x100 matrix with lots of zeroes. For a weighted graph, instead of 1s and 0s, we can store the weight of the edge. In that case, to indicate that there is no edge we can put a safely large value (we can call it INF (infinity) ). The following firgure shows the Adjacency Matrix of Graphs in Fig[ ?? ]

[ Add figure(s) for adjacency matrix ]


While the adjacency list saves a lot of space for sparse graphs, we cannot instantly access an edge. While we can access any edge instantly in adjacency matrix, it takes a lot of space (space is fine for graphs even with n = 1000 ) and to visit all the neighbors of a vertex, we have to traverse all the vertices in the graph ( the whole row corresponding to the vertex ), which takes quite some time. So there is a trade-off between the two representations, and one has to decide depending on the problem.


 

Hmm.. enough with all that theory part. Now lets see a very simple technique and solve some problems using it :)

Depth First Search (DFS)

Now we know what a graph is and how to represent it. Given a graph G, how to traverse the graph ? How do we know whether a vertex u is connected to a vertex v (by some path) ? How many connected components are there in G ? How to mark all the nodes that can be reached from a vertex v (  Flood-Fill ) ?

Tutorials and source codes related to Graph Theory

Depth First Search in Graphs - Tutorial and C Program
Breadth First Search in Graphs - Tutorial and C Program
Minimum Spanning Tree - Kruskal Algorithm - Tutorial and C Program
Dijkstra Shortest Path Algorithm - Tutorial and C Program

 In case you want to see a visualization of depth-first-search and breadth-first-search you might find this page useful: http://www.thelearningpoint.net/computer-science/graph-algorithms

 


Comments

  • Login or Register to post a comment.

where are the figures???????

arun chauhan @ 4 Jan 2010 08:35 PM

where are the figures???????

plz complete this tutorial

shrishkrish @ 24 Jan 2010 05:05 PM

plz complete this tutorial and write some more  these tutorials are quite helpful

I suggest that admin should ask each programmer of month to submit a tutorial (write-up) :P

Can u please add figures to

akashag1001 @ 1 Oct 2010 10:55 PM

Can u please add figures to this tutorial; it denies its essence w/o pictures.

Figures are not there, please

chouhan @ 12 Aug 2011 09:58 PM
Figures are not there, please add the images
CodeChef is a non-commercial competitive programming community
  • About CodeChef
  • About Directi
  • CEO's Corner
  • C-Programming
  • Programming Languages
  • Contact Us
© 2009 Directi Group. All Rights Reserved. CodeChef uses SPOJ © by Sphere Research Labs
In order to report copyright violations of any kind, send in an email to copyright@codechef.com
CodeChef a product of Directi
The time now is:
CodeChef - A Platform for Aspiring Programmers

CodeChef was created as a platform to help programmers make it big in the world of algorithms, computer programming and programming contests. At CodeChef we work hard to revive the geek in you by hosting a programming contest at the start of the month and another smaller programming challenge in the middle of the month. We also aim to have training sessions and discussions related to algorithms, binary search, technicalities like array size and the likes. Apart from providing a platform for programming competitions, CodeChef also has various algorithm tutorials and forum discussions to help those who are new to the world of computer programming.

Practice Section - A Place to hone your 'Computer Programming Skills'

Try your hand at one of our many practice problems and submit your solution in a language of your choice. Our programming contest judge accepts solutions in over 35+ programming languages. Preparing for coding contests were never this much fun! Receive points, and move up through the CodeChef ranks. Use our practice section to better prepare yourself for the multiple programming challenges that take place through-out the month on CodeChef.

Compete - Monthly Programming Contests and Cook-offs

Here is where you can show off your computer programming skills. Take part in our 10 day long monthly coding contest and the shorter format Cook-off coding contest. Put yourself up for recognition and win great prizes. Our programming contests have prizes worth up to Rs.20,000 and $700lots more CodeChef goodies up for grabs.

Discuss

Are you new to computer programming? Do you need help with algorithms? Then be a part of CodeChef's Forums and interact with all our programmers - they love helping out other programmers and sharing their ideas. Have discussions around binary search, array size, branch-and-bound, Dijkstra's algorithm, Encryption algorithm and more by visiting the CodeChef Forums and Wiki section.

CodeChef Community

As part of our Educational initiative, we give institutes the opportunity to associate with CodeChef in the form of Campus Chapters. Hosting online programming competitions is not the only feature on CodeChef. You can also host a coding contest for your institute on CodeChef, organize an algorithm event and be a guest author on our blog.

Go For Gold

The Go for Gold Initiative was launched about a year after CodeChef was incepted, to help prepare Indian students for the ACM ICPC World Finals competition. In the run up to the ACM ICPC competition, the Go for Gold initiative uses CodeChef as a platform to train students for the ACM ICPC competition via multiple warm up contests. As an added incentive the Go for Gold initiative is also offering over Rs.8 lacs to the Indian team that beats the 29th position at the ACM ICPC world finals. Find out more about the Go for Gold and the ACM ICPC competition here.

Domain Name Registration, Web hosting, and Website Design provided by BigRock.com