SlideShare a Scribd company logo
CS Dudes
meetup #1. Graph theory basics
1
Snakes & Ladders
2
Brute-force solution
Recursively inspect every possible combination of moves O(n!)
Introduce memo table to improve performance
Invent DP version
3
GRAPH is a structure
amounting to a set of objects in
which some pairs of the objects
are in some sense "related"
4
Graph types
Directed/undirected
Weighted/unweighted
Cyclic/acyclic
Connected/disconnected
5
Tree - acyclic connected
undirected graph
6
Applications
Routes
Optimizations
Scheduling
Fuzzy search
Performance improvements
Classifications
7
Representation in CS
8
Adjacency matrix
A
E
B
D
C
A B C D E
A 0 1 0 0 1
B 1 0 1 1 1
C 0 1 0 1 0
D 0 1 1 0 1
E 1 1 0 1 0
9
Adjacency list
A
E
B
D
C
A B E
B A C D E
C B D
D B C E
E A B D
10
Ways to find routes
11
One source and One Destination
A* Search Algorithm
(For Unweighted as well as Weighted Graphs)
12
One Source, All Destination
BFS (For Unweighted Graphs)
Dijkstra (For Weighted Graphs without negative weights)
Bellman Ford (For Weighted Graphs with negative weights)
13
Between every pair of nodes
Floyd-Warshall
Johnson’s Algorithm
14
BFS in action
15
BFS in action. Shortest routes from A
A
E
B
D
C
F
A
Inspection queue:
A B E
B A C D E
C B D F
D B C E
E A B D
F C
16
BFS in action. Shortest routes from A
A
E
B
D
C
F
A
Inspection queue:
A B E
B A C D E
C B D F
D B C E
E A B D
F C
1
1
B
E
0
17
BFS in action. Shortest routes from A
A
E
B
D
C
F
Inspection queue:
A B E
B A C D E
C B D F
D B C E
E A B D
F C
1
1
B
E
0
C
D
2
2
18
BFS in action. Shortest routes from A
A
E
B
D
C
F
Inspection queue:
A B E
B A C D E
C B D F
D B C E
E A B D
F C
1
1
E
0
C
D
2
2
19
BFS in action. Shortest routes from A
A
E
B
D
C
F
Inspection queue:
A B E
B A C D E
C B D F
D B C E
E A B D
F C
1
1
0 C
D2
2
F
3
20
BFS in action. Shortest routes from A
A
E
B
D
C
F
Inspection queue:
A B E
B A C D E
C B D F
D B C E
E A B D
F C
1
1
0 D
2
2
F
3
21
BFS in action. Shortest routes from A
A
E
B
D
C
F
Inspection queue:
A B E
B A C D E
C B D F
D B C E
E A B D
F C
1
1
0 F
2
2
3
22
Implementation
23
Snakes & Ladders
24
public class Main {
public static void main( String[] args ) {
Board board = new Board( 6, 5 );
board.addLadder( 3, 22 );
board.addLadder( 5, 8 );
board.addLadder( 11, 26 );
board.addLadder( 20, 29 );
board.addSnake( 17, 4 );
board.addSnake( 19, 7 );
board.addSnake( 21, 9 );
board.addSnake( 27, 1 );
MinDiceSolver solver = new MinDiceSolver( board );
System.out.println(
"Min dice rolls number is " + solver.getMinDiceRolls()
);
}
} 25
public class Board {
private int[] paths;
public Board( int width, int height ) {
paths = new int[width * height];
for ( int i = 0; i < paths.length; i++ ) {
paths[i] = i + 1;
}
}
public void addLadder( int from, int to ) { paths[from - 1] = to - 1; }
public void addSnake( int from, int to ) { paths[from - 1] = to - 1; }
}
26
public class MinDiceSolver {
private static final int DICE_SIZE = 6;
private final Board board;
public MinDiceSolver( Board board ) { this.board = board; }
private static class QEntry {
private int cellid;
private int distance;
public QEntry( int cellid, int distance ) {
this.cellid = cellid;
this.distance = distance;
}
}
public int getMinDiceRolls() { ... } // <!-- need to implement
}
27
public int getMinDiceRolls() {
int[] paths = board.getPaths();
boolean[] visited = new boolean[ paths.length ];
QEntry current = new QEntry( 0, 0 );
visited[0] = true;
Queue<QEntry> q = new LinkedList<>();
q.add( current );
while ( !q.isEmpty() ) {
current = q.poll();
if ( current.cellid == paths.length - 1 ) { break; }
for ( int i = current.cellid + 1; ( i <= current.cellid + DICE_SIZE ) && i < paths.length; i++ ) {
if ( !visited[i] ) {
q.add( new QEntry( paths[i], current.distance + 1 ) );
visited[i] = true;
}
}
}
return current.distance;
}
28
Gimme the code!
Grab & run:
$ git clone https://gitlab.com/csdudes/meetup1.git
$ cd metup1/
$ ./gradlew run
29

More Related Content

PDF
[Question Paper] Fundamentals of Digital Computing (Revised Course) [April / ...
PPTX
Signal Flow Graph ( control system)
ODP
Recursion and Functional Programming
PDF
Michal Malohlava presents: Open Source H2O and Scala
PPT
Block diagram reduction techniques
PDF
StrataGEM: A Generic Petri Net Verification Framework
PPTX
Block Diagram Reduction
PPTX
Block diagram
[Question Paper] Fundamentals of Digital Computing (Revised Course) [April / ...
Signal Flow Graph ( control system)
Recursion and Functional Programming
Michal Malohlava presents: Open Source H2O and Scala
Block diagram reduction techniques
StrataGEM: A Generic Petri Net Verification Framework
Block Diagram Reduction
Block diagram

What's hot (20)

PPT
Application of Non-linear Electronics in Digital Communication
PPTX
Single sourceshortestpath by emad
PPTX
Signal flow graph
PPTX
Anti patterns
PDF
Bellman ford algorithm
PDF
4th Semester M Tech: Computer Science and Engineering (Jun-2016) Question Papers
PDF
Ece512 h1 20139_621386735458ece512_test2_solutions
PDF
EC202 SIGNALS & SYSTEMS PREVIOUS QUESTION PAPER
PPT
Lec9 Intro to Computer Engineering by Hsien-Hsin Sean Lee Georgia Tech -- Com...
PPTX
Block diagrams and signal flow graphs
PDF
E04011 03 3339
PPTX
A* (aster) Search Algorithm
PDF
PPT
Algorithm.ppt
PPTX
Bellman ford algorithm
PPTX
Specifying compatible sharing in data structures
PPT
Single source stortest path bellman ford and dijkstra
PPTX
Complete and Interpretable Conformance Checking of Business Processes
PDF
5th Semester Electronic and Communication Engineering (June/July-2015) Questi...
PDF
Digital Signals and System (October – 2016) [Revised Syllabus | Question Paper]
Application of Non-linear Electronics in Digital Communication
Single sourceshortestpath by emad
Signal flow graph
Anti patterns
Bellman ford algorithm
4th Semester M Tech: Computer Science and Engineering (Jun-2016) Question Papers
Ece512 h1 20139_621386735458ece512_test2_solutions
EC202 SIGNALS & SYSTEMS PREVIOUS QUESTION PAPER
Lec9 Intro to Computer Engineering by Hsien-Hsin Sean Lee Georgia Tech -- Com...
Block diagrams and signal flow graphs
E04011 03 3339
A* (aster) Search Algorithm
Algorithm.ppt
Bellman ford algorithm
Specifying compatible sharing in data structures
Single source stortest path bellman ford and dijkstra
Complete and Interpretable Conformance Checking of Business Processes
5th Semester Electronic and Communication Engineering (June/July-2015) Questi...
Digital Signals and System (October – 2016) [Revised Syllabus | Question Paper]
Ad

Similar to Graph theory basics (20)

PDF
Pathfinding in games
PPT
Algorithm
PPTX
Data Structures - Lecture 10 [Graphs]
DOCX
2Part I1. Answer questions for the following graph, if .docx
PDF
Unit ii divide and conquer -2
PPTX
Lec 15-graph Searching in data structure and lgorithm.pptx
PPTX
Basic Graph Algorithms Vertex (Node): lk
PPTX
logic.pptx
PDF
AI Lab print ptu universty st soldier collage .pdf
PPTX
Data structure Basic ,Fundamentals, Types
PDF
Shoot-for-A-Star
PPT
22-graphs1-dfs-bfs.ppt
PDF
PATH FINDING SOLUTIONS FOR GRID BASED GRAPH
PDF
AI Lab menu for ptu students and easy to use and best quality and help for 6t...
DOCX
Divide-and-Conquer & Dynamic ProgrammingDivide-and-Conqu.docx
PPT
22-graphs1-dfs-bfs.ppt odiehehei7hoh97ho7bi6vi6go7gp
PPT
Data Structures-Non Linear DataStructures-Graphs
PPTX
WEB DEVELOPMET FRONT END WITH ADVANCED RECEAT
PPTX
Data structure Graph PPT ( BFS & DFS ) NOTES
PPTX
DATA STRUCTURES.pptx
Pathfinding in games
Algorithm
Data Structures - Lecture 10 [Graphs]
2Part I1. Answer questions for the following graph, if .docx
Unit ii divide and conquer -2
Lec 15-graph Searching in data structure and lgorithm.pptx
Basic Graph Algorithms Vertex (Node): lk
logic.pptx
AI Lab print ptu universty st soldier collage .pdf
Data structure Basic ,Fundamentals, Types
Shoot-for-A-Star
22-graphs1-dfs-bfs.ppt
PATH FINDING SOLUTIONS FOR GRID BASED GRAPH
AI Lab menu for ptu students and easy to use and best quality and help for 6t...
Divide-and-Conquer & Dynamic ProgrammingDivide-and-Conqu.docx
22-graphs1-dfs-bfs.ppt odiehehei7hoh97ho7bi6vi6go7gp
Data Structures-Non Linear DataStructures-Graphs
WEB DEVELOPMET FRONT END WITH ADVANCED RECEAT
Data structure Graph PPT ( BFS & DFS ) NOTES
DATA STRUCTURES.pptx
Ad

More from Alexey Tokar (9)

PPTX
Fantastic caches and where to find them
PPTX
Conway's transformation
PPTX
Bug prediction + sdlc automation
PPTX
Bots on guard of sdlc
PPTX
Bug prediction based on your code history
PPTX
Extend your REST API
PPTX
Найти иглоку в стоге сена
PPTX
MongoDB в продакшен - миф или реальность?
PPTX
когда тексты не только слова
Fantastic caches and where to find them
Conway's transformation
Bug prediction + sdlc automation
Bots on guard of sdlc
Bug prediction based on your code history
Extend your REST API
Найти иглоку в стоге сена
MongoDB в продакшен - миф или реальность?
когда тексты не только слова

Recently uploaded (20)

PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PDF
Anesthesia in Laparoscopic Surgery in India
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PPTX
Lesson notes of climatology university.
PPTX
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
RTP_AR_KS1_Tutor's Guide_English [FOR REPRODUCTION].pdf
PDF
VCE English Exam - Section C Student Revision Booklet
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PDF
01-Introduction-to-Information-Management.pdf
PPTX
master seminar digital applications in india
PPTX
Cell Structure & Organelles in detailed.
PPTX
GDM (1) (1).pptx small presentation for students
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
Module 4: Burden of Disease Tutorial Slides S2 2025
Anesthesia in Laparoscopic Surgery in India
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Lesson notes of climatology university.
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
O5-L3 Freight Transport Ops (International) V1.pdf
RTP_AR_KS1_Tutor's Guide_English [FOR REPRODUCTION].pdf
VCE English Exam - Section C Student Revision Booklet
human mycosis Human fungal infections are called human mycosis..pptx
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
01-Introduction-to-Information-Management.pdf
master seminar digital applications in india
Cell Structure & Organelles in detailed.
GDM (1) (1).pptx small presentation for students
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
Chapter 2 Heredity, Prenatal Development, and Birth.pdf

Graph theory basics

  • 1. CS Dudes meetup #1. Graph theory basics 1
  • 3. Brute-force solution Recursively inspect every possible combination of moves O(n!) Introduce memo table to improve performance Invent DP version 3
  • 4. GRAPH is a structure amounting to a set of objects in which some pairs of the objects are in some sense "related" 4
  • 6. Tree - acyclic connected undirected graph 6
  • 9. Adjacency matrix A E B D C A B C D E A 0 1 0 0 1 B 1 0 1 1 1 C 0 1 0 1 0 D 0 1 1 0 1 E 1 1 0 1 0 9
  • 10. Adjacency list A E B D C A B E B A C D E C B D D B C E E A B D 10
  • 11. Ways to find routes 11
  • 12. One source and One Destination A* Search Algorithm (For Unweighted as well as Weighted Graphs) 12
  • 13. One Source, All Destination BFS (For Unweighted Graphs) Dijkstra (For Weighted Graphs without negative weights) Bellman Ford (For Weighted Graphs with negative weights) 13
  • 14. Between every pair of nodes Floyd-Warshall Johnson’s Algorithm 14
  • 16. BFS in action. Shortest routes from A A E B D C F A Inspection queue: A B E B A C D E C B D F D B C E E A B D F C 16
  • 17. BFS in action. Shortest routes from A A E B D C F A Inspection queue: A B E B A C D E C B D F D B C E E A B D F C 1 1 B E 0 17
  • 18. BFS in action. Shortest routes from A A E B D C F Inspection queue: A B E B A C D E C B D F D B C E E A B D F C 1 1 B E 0 C D 2 2 18
  • 19. BFS in action. Shortest routes from A A E B D C F Inspection queue: A B E B A C D E C B D F D B C E E A B D F C 1 1 E 0 C D 2 2 19
  • 20. BFS in action. Shortest routes from A A E B D C F Inspection queue: A B E B A C D E C B D F D B C E E A B D F C 1 1 0 C D2 2 F 3 20
  • 21. BFS in action. Shortest routes from A A E B D C F Inspection queue: A B E B A C D E C B D F D B C E E A B D F C 1 1 0 D 2 2 F 3 21
  • 22. BFS in action. Shortest routes from A A E B D C F Inspection queue: A B E B A C D E C B D F D B C E E A B D F C 1 1 0 F 2 2 3 22
  • 25. public class Main { public static void main( String[] args ) { Board board = new Board( 6, 5 ); board.addLadder( 3, 22 ); board.addLadder( 5, 8 ); board.addLadder( 11, 26 ); board.addLadder( 20, 29 ); board.addSnake( 17, 4 ); board.addSnake( 19, 7 ); board.addSnake( 21, 9 ); board.addSnake( 27, 1 ); MinDiceSolver solver = new MinDiceSolver( board ); System.out.println( "Min dice rolls number is " + solver.getMinDiceRolls() ); } } 25
  • 26. public class Board { private int[] paths; public Board( int width, int height ) { paths = new int[width * height]; for ( int i = 0; i < paths.length; i++ ) { paths[i] = i + 1; } } public void addLadder( int from, int to ) { paths[from - 1] = to - 1; } public void addSnake( int from, int to ) { paths[from - 1] = to - 1; } } 26
  • 27. public class MinDiceSolver { private static final int DICE_SIZE = 6; private final Board board; public MinDiceSolver( Board board ) { this.board = board; } private static class QEntry { private int cellid; private int distance; public QEntry( int cellid, int distance ) { this.cellid = cellid; this.distance = distance; } } public int getMinDiceRolls() { ... } // <!-- need to implement } 27
  • 28. public int getMinDiceRolls() { int[] paths = board.getPaths(); boolean[] visited = new boolean[ paths.length ]; QEntry current = new QEntry( 0, 0 ); visited[0] = true; Queue<QEntry> q = new LinkedList<>(); q.add( current ); while ( !q.isEmpty() ) { current = q.poll(); if ( current.cellid == paths.length - 1 ) { break; } for ( int i = current.cellid + 1; ( i <= current.cellid + DICE_SIZE ) && i < paths.length; i++ ) { if ( !visited[i] ) { q.add( new QEntry( paths[i], current.distance + 1 ) ); visited[i] = true; } } } return current.distance; } 28
  • 29. Gimme the code! Grab & run: $ git clone https://gitlab.com/csdudes/meetup1.git $ cd metup1/ $ ./gradlew run 29