SlideShare a Scribd company logo
1 of 29
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

What's hot

Application of Non-linear Electronics in Digital Communication
Application of Non-linear Electronics in Digital CommunicationApplication of Non-linear Electronics in Digital Communication
Application of Non-linear Electronics in Digital CommunicationMohammad reza Zahabi
 
Single sourceshortestpath by emad
Single sourceshortestpath by emadSingle sourceshortestpath by emad
Single sourceshortestpath by emadKazi Emad
 
Bellman ford algorithm
Bellman ford algorithmBellman ford algorithm
Bellman ford algorithmA. S. M. Shafi
 
Ece512 h1 20139_621386735458ece512_test2_solutions
Ece512 h1 20139_621386735458ece512_test2_solutionsEce512 h1 20139_621386735458ece512_test2_solutions
Ece512 h1 20139_621386735458ece512_test2_solutionsnadia abd
 
EC202 SIGNALS & SYSTEMS PREVIOUS QUESTION PAPER
EC202 SIGNALS & SYSTEMS PREVIOUS QUESTION PAPEREC202 SIGNALS & SYSTEMS PREVIOUS QUESTION PAPER
EC202 SIGNALS & SYSTEMS PREVIOUS QUESTION PAPERVISHNUPRABHANKAIMAL
 
Lec9 Intro to Computer Engineering by Hsien-Hsin Sean Lee Georgia Tech -- Com...
Lec9 Intro to Computer Engineering by Hsien-Hsin Sean Lee Georgia Tech -- Com...Lec9 Intro to Computer Engineering by Hsien-Hsin Sean Lee Georgia Tech -- Com...
Lec9 Intro to Computer Engineering by Hsien-Hsin Sean Lee Georgia Tech -- Com...Hsien-Hsin Sean Lee, Ph.D.
 
Block diagrams and signal flow graphs
Block diagrams and signal flow graphsBlock diagrams and signal flow graphs
Block diagrams and signal flow graphsHussain K
 
E04011 03 3339
E04011 03 3339E04011 03 3339
E04011 03 3339IJMER
 
A* (aster) Search Algorithm
A* (aster) Search AlgorithmA* (aster) Search Algorithm
A* (aster) Search AlgorithmSanzid Kawsar
 
Specifying compatible sharing in data structures
Specifying compatible sharing in data structuresSpecifying compatible sharing in data structures
Specifying compatible sharing in data structuresAsankhaya Sharma
 
Single source stortest path bellman ford and dijkstra
Single source stortest path bellman ford and dijkstraSingle source stortest path bellman ford and dijkstra
Single source stortest path bellman ford and dijkstraRoshan Tailor
 
Complete and Interpretable Conformance Checking of Business Processes
Complete and Interpretable Conformance Checking of Business ProcessesComplete and Interpretable Conformance Checking of Business Processes
Complete and Interpretable Conformance Checking of Business ProcessesMarlon Dumas
 
Digital Signals and System (October – 2016) [Revised Syllabus | Question Paper]
Digital Signals and System (October  – 2016) [Revised Syllabus | Question Paper]Digital Signals and System (October  – 2016) [Revised Syllabus | Question Paper]
Digital Signals and System (October – 2016) [Revised Syllabus | Question Paper]Mumbai B.Sc.IT Study
 

What's hot (20)

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

Similar to Graph theory basics

artificial intelligence
artificial intelligence artificial intelligence
artificial intelligence ilias ahmed
 
How to add an optimization for C# to RyuJIT
How to add an optimization for C# to RyuJITHow to add an optimization for C# to RyuJIT
How to add an optimization for C# to RyuJITEgor Bogatov
 
IAP presentation-1.pptx
IAP presentation-1.pptxIAP presentation-1.pptx
IAP presentation-1.pptxHirazNor
 
Link Prediction in the Real World
Link Prediction in the Real WorldLink Prediction in the Real World
Link Prediction in the Real WorldBalaji Ganesan
 
IAP PPT-1.pptx
IAP PPT-1.pptxIAP PPT-1.pptx
IAP PPT-1.pptxHirazNor
 
Dzanan_Bajgoric_C2CUDA_MscThesis_Present
Dzanan_Bajgoric_C2CUDA_MscThesis_PresentDzanan_Bajgoric_C2CUDA_MscThesis_Present
Dzanan_Bajgoric_C2CUDA_MscThesis_PresentDžanan Bajgorić
 
Presentation on Breadth First Search (BFS)
Presentation on Breadth First Search (BFS)Presentation on Breadth First Search (BFS)
Presentation on Breadth First Search (BFS)Shuvongkor Barman
 
Gate Computer Science Solved Paper 2007
Gate Computer Science Solved Paper 2007 Gate Computer Science Solved Paper 2007
Gate Computer Science Solved Paper 2007 Rohit Garg
 
Digital logic circuit
Digital logic circuit Digital logic circuit
Digital logic circuit Prabhu R
 
Self Managed and Automatically Reconfigurable Stream Processing - Vasiliki Ka...
Self Managed and Automatically Reconfigurable Stream Processing - Vasiliki Ka...Self Managed and Automatically Reconfigurable Stream Processing - Vasiliki Ka...
Self Managed and Automatically Reconfigurable Stream Processing - Vasiliki Ka...Flink Forward
 
Self-managed and automatically reconfigurable stream processing
Self-managed and automatically reconfigurable stream processingSelf-managed and automatically reconfigurable stream processing
Self-managed and automatically reconfigurable stream processingVasia Kalavri
 
Functional Design Explained (David Sankel CppCon 2015)
Functional Design Explained (David Sankel CppCon 2015)Functional Design Explained (David Sankel CppCon 2015)
Functional Design Explained (David Sankel CppCon 2015)sankeld
 
Distributed computation and reconfiguration in actively dynamic networks
Distributed computation and reconfiguration in actively dynamic networksDistributed computation and reconfiguration in actively dynamic networks
Distributed computation and reconfiguration in actively dynamic networksPeter Kos
 

Similar to Graph theory basics (20)

artificial intelligence
artificial intelligence artificial intelligence
artificial intelligence
 
How to add an optimization for C# to RyuJIT
How to add an optimization for C# to RyuJITHow to add an optimization for C# to RyuJIT
How to add an optimization for C# to RyuJIT
 
VerilogHDL_Utkarsh_kulshrestha
VerilogHDL_Utkarsh_kulshresthaVerilogHDL_Utkarsh_kulshrestha
VerilogHDL_Utkarsh_kulshrestha
 
IAP presentation-1.pptx
IAP presentation-1.pptxIAP presentation-1.pptx
IAP presentation-1.pptx
 
Link Prediction in the Real World
Link Prediction in the Real WorldLink Prediction in the Real World
Link Prediction in the Real World
 
IAP PPT-1.pptx
IAP PPT-1.pptxIAP PPT-1.pptx
IAP PPT-1.pptx
 
Dzanan_Bajgoric_C2CUDA_MscThesis_Present
Dzanan_Bajgoric_C2CUDA_MscThesis_PresentDzanan_Bajgoric_C2CUDA_MscThesis_Present
Dzanan_Bajgoric_C2CUDA_MscThesis_Present
 
5.2_video_slides.pptx
5.2_video_slides.pptx5.2_video_slides.pptx
5.2_video_slides.pptx
 
Presentation on Breadth First Search (BFS)
Presentation on Breadth First Search (BFS)Presentation on Breadth First Search (BFS)
Presentation on Breadth First Search (BFS)
 
Gate Computer Science Solved Paper 2007
Gate Computer Science Solved Paper 2007 Gate Computer Science Solved Paper 2007
Gate Computer Science Solved Paper 2007
 
Digital logic circuit
Digital logic circuit Digital logic circuit
Digital logic circuit
 
Cs 2003
Cs 2003Cs 2003
Cs 2003
 
Unit 4 dica
Unit 4 dicaUnit 4 dica
Unit 4 dica
 
Polesrootlocus_IISC.pdf
Polesrootlocus_IISC.pdfPolesrootlocus_IISC.pdf
Polesrootlocus_IISC.pdf
 
Self Managed and Automatically Reconfigurable Stream Processing - Vasiliki Ka...
Self Managed and Automatically Reconfigurable Stream Processing - Vasiliki Ka...Self Managed and Automatically Reconfigurable Stream Processing - Vasiliki Ka...
Self Managed and Automatically Reconfigurable Stream Processing - Vasiliki Ka...
 
Self-managed and automatically reconfigurable stream processing
Self-managed and automatically reconfigurable stream processingSelf-managed and automatically reconfigurable stream processing
Self-managed and automatically reconfigurable stream processing
 
Functional Design Explained (David Sankel CppCon 2015)
Functional Design Explained (David Sankel CppCon 2015)Functional Design Explained (David Sankel CppCon 2015)
Functional Design Explained (David Sankel CppCon 2015)
 
Distributed computation and reconfiguration in actively dynamic networks
Distributed computation and reconfiguration in actively dynamic networksDistributed computation and reconfiguration in actively dynamic networks
Distributed computation and reconfiguration in actively dynamic networks
 
Graphs
GraphsGraphs
Graphs
 
Gate-Cs 2007
Gate-Cs 2007Gate-Cs 2007
Gate-Cs 2007
 

More from Alexey Tokar

Fantastic caches and where to find them
Fantastic caches and where to find themFantastic caches and where to find them
Fantastic caches and where to find themAlexey Tokar
 
Conway's transformation
Conway's transformationConway's transformation
Conway's transformationAlexey Tokar
 
Bug prediction + sdlc automation
Bug prediction + sdlc automationBug prediction + sdlc automation
Bug prediction + sdlc automationAlexey Tokar
 
Bots on guard of sdlc
Bots on guard of sdlcBots on guard of sdlc
Bots on guard of sdlcAlexey Tokar
 
Bug prediction based on your code history
Bug prediction based on your code historyBug prediction based on your code history
Bug prediction based on your code historyAlexey Tokar
 
Extend your REST API
Extend your REST APIExtend your REST API
Extend your REST APIAlexey Tokar
 
Найти иглоку в стоге сена
Найти иглоку в стоге сенаНайти иглоку в стоге сена
Найти иглоку в стоге сенаAlexey Tokar
 
MongoDB в продакшен - миф или реальность?
MongoDB в продакшен - миф или реальность?MongoDB в продакшен - миф или реальность?
MongoDB в продакшен - миф или реальность?Alexey Tokar
 
когда тексты не только слова
когда тексты не только словакогда тексты не только слова
когда тексты не только словаAlexey Tokar
 

More from Alexey Tokar (9)

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

Recently uploaded

Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
PSYCHIATRIC History collection FORMAT.pptx
PSYCHIATRIC   History collection FORMAT.pptxPSYCHIATRIC   History collection FORMAT.pptx
PSYCHIATRIC History collection FORMAT.pptxPoojaSen20
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991RKavithamani
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 

Recently uploaded (20)

Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
PSYCHIATRIC History collection FORMAT.pptx
PSYCHIATRIC   History collection FORMAT.pptxPSYCHIATRIC   History collection FORMAT.pptx
PSYCHIATRIC History collection FORMAT.pptx
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 

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