15 views

Uploaded by Sameera Horawalavithana

- Matching
- GCSE Mock Paper
- zozzle
- Assembly Line
- Dp Intro
- Data Structure and Algorithm List From Jami Sir
- 2002-10-17
- dfs and bfs
- Graphs
- final2
- Edge Magic Total Labeling of Prism
- Advance Algorithm
- DFS-QoS-CI2
- p4-freegraf
- Syllabus_Network_Economics.pdf
- Scheduling
- Syllabus
- Graphs
- Combinatorial Enumeration
- Blockchain Accelerates Insurance Transformation Fs

You are on page 1of 12

GROUP 03 10001441 | HETTIARACHCHI K.H.A.P.L 10001697 | UDAYANGANI W.K 10001794 | EDWARD M.S 10002091 | MUKADANGE H.R *10002103 | HORAWALAVITHANA Y.S | pradeep90lakmal@gmail.com | udayanganiwijesekara@gmail.com | sanjithchendrika@gmail.com | hazru90@gmail.com | sam2010ucsc@gmail.com

**[GRAPH TRAVERSAL & SHORTEST PATH ]
**

SCS 2009 – GROUP ASSIGNMENT 02

.................................................................................................................1 Greedy Algorithm ........................................................................................................................ 11 ............................................................................................................................................................ 4 2... 7 3. 3 1.............................................................. 3 1.............................. 10 4.........................................................................................................................................................................................................................................0 Q 02 – SOLVING MAZE .....2 Maze Representation .......0 Q 01 – MARRIAGE PROBLEM......................1 Problem Overview ........................................................................................................................................................... 7 3....................................................................2 Dynamic Algorithm ..................................................................................................................................0 Q 01 – NEW MACHINE PROBLEM ............................................................................. 4 2......................4 Advanced Work .......5 Analysis ...............5 Optimal Solutions ............................................................................................................................................................. 5 2...................................2 Approach to Solution ...4 Pseudo Code .................... 2 1........................................................................... 2 1............................................................................................................................................................................................................................ 4 2.......................................................................................... 8 3....................................................................................................................................................... 7 3..0 Q 01 –COIN PROBLEM... 9 4......................................................................................3 Why Dynamic Programming? ......2 Approach to Solution .....................3 Maze Solving............................................. 4 2.......3 Algorithms Used ...........................................4 Optimal value Function ..................................1 Problem Overview ........ 7 3.....1 Contents 1........................................1 Problem Overview ............... 10 4............................... 2 1................................................................................. 5 3......

if for every subset S of X.1 Problem Overview There are two groups of men and women who desire to get married. We would not have edges between women or men individually. So each vertex can be categorized into two levels while all edges are between those two levels.2 Approach to Solution Suppose that a group contains w single women and m single men. bipartite.” . if |X| = |Y | then there does not exist a perfect matching for G. This situation can be identified as a graph once vertex class represents (w + m) women and men. That is.0 Q 01 – MARRIAGE PROBLEM 1. Participants of each group indicate who among the opposite sex would be acceptable as a potential spouse. and every man to at most one woman. What is Perfect Matching? Perfect Matching (or complete matching) describes that no unmatched vertices can be found in the graph at the end. which matches all vertices in the graph. then the number of elements in X is equal to the number of elements in Y.10 (Perfect Matching) : A perfect matching exists on a bipartite graph G with bipartition X and Y if and only if for every subset S of X we have |S| ≤ |N (S)|and |X| = |Y |. 1. itself. Every sub graph H of a bipartite graph G is. Properties of Bipartite graphs If G is a k-regular bipartite graph with k > 0 and the bipartition of G is X and Y .1. Every perfect matching is maximum. the number of elements in S is less than or equal to the number of elements in the neighborhood of S. Every woman can be married to at most one man. “Theorem 2. A bipartite graph contains no odd cycles. Then we would have the bipartite graph which this marriage problem does not violate the bipartite constraints.0 Q 01 – MARRIAGE PROBLEM 2 1. while each women Wi is joined by an edge to a man Mi if they two like each other. Every vertex in the graph matters to exactly one edge. Given a bipartite graph G with bipartition X and Y .

describes the matching.. M 1. Matching(Graph){ 1) Run BFS & set each vertex in to two vertex class & check whether the graph is bipartite 2) Check constraints |S| ≤ |Adj (S)|and |W| = |M | 3) Repeat Forever a.. In implementation. then flip the edges . at subsequent levels of the search. Perform BFS to set all vertices into layers where the unmatched vertex W0 starts the procedure and forms the first layer. In any bipartite graph. If found an augmenting path. Each unmatched edges been traversed. c. when each node been visited via BFS.0 Q 01 – MARRIAGE PROBLEM 3 1. check the current cycle is odd or even. iff it ends in the shortest augmenting path.3 Algorithms Used Breadth First Search (BFS) in graph algorithm can be used with small modification to check whether the graph is bipartite or not. All unmatched vertices in M at each layer put down to a set S.1.4 Pseudo Code Suppose that W and M are two vertex classes and M. if we have an algorithm ﬁnding an M -augmenting path for any matching M (if it exists). then we can ﬁnd a maximum cardinality matching: we iteratively ﬁnd matchings’ M0. Since bipartite graph doesn’t contain odd-length cycles. the traversed edges are required to alternate between unmatched and matched. Start with an arbitrary matching b. Hopcroft–Karp algorithm takes a bipartite graph as input and provides a maximum matching. Assume that the graph been created according to each person likeness. ii. with |M i|=i. Starting and ending of the algorithm takes place from a unmatched vertex.. partition level exchange between each node and its adjacency nodes. until we have a matching Mk such that there does not exist any M kaugmenting path 1. For all unmatched vertices i..

we have to represent it as a graph & solve it using appropriate graph traversal algorithm.5 |E|).2. For each key. Using such approach. In sparse graph Hopcroft–Karp performs worst case since each person likenesses are less and have slightly few edges. } 1. Graph representation is simplified in Python programming language by introducing Dictionary data structure. the corresponding value is a list containing the nodes that are connected by a direct arc from this . BFS both must visit each node and each edge in order to list Vn. 2. Edges represent the pairs of cells which you can move between. We can find at most |V| augmenting paths.5 Analysis With V vertices and U edges. the worst-case running time must be at least O(V+E) – linear time. In this case.2 Maze Representation We can simply look into the maze and can identify each vertices required. 2.0 Q 02 – SOLVING MAZE 2.1 Problem Overview Given maze.0 Q 02 – SOLVING MAZE 4 d. Each vertex represents the passable hole in the graph. Dictionary whose keys are the nodes of the graph. Else stop and report the maximum path to update M. each phase in the algorithm BFS has been taken place to find an augmenting path. the time complexity is improved to O(|V|0. We can make this as a Directed or Undirected graph since that does not violate the solution. So the total time O(|V||V+E|). But averagely dense graph achieves best results. Above algorithm performs different Running time between sparse & dense graphs. And the graph structure benefit is that it takes up a lot less space if the maze passes are very sparse with compared to adjacency matrix. We can make an improvement by finding augmenting path at each iteration parallel in unmatched vertices.

we can use pixel replication to set an adjacency matrix. 'I'].'C'. Undirected graph representation for Maze in Python Dic: Graph={'A':['B'. you may find the suboptimal solution (and stop there) before you find the real shortest path. In python it just takes few-code to transform an image into matrix form with color values.'B':['A'. BFS gives us the optimal solution – the shortest path.'J':['E'.'H'].'C']. But with all Python patterns to implement graph.'F':['B'.'F'].'G'].'F'].'I':['E'.'D'].2. if you are just searching for a path from one vertex to another.'E'. But we use cheap procedure that look into the maze & identify holes that could be transformed into vertices and edges in the graph.'L':['K']} 2.'C':['A'.'J'].'D':['A'.0 Q 02 – SOLVING MAZE 5 node.'E':[' B'. But solving maze doesn’t matter where it is the shortest path or not. They have the same time complexity O(|V+E|). With all conclusions we use DFS that is a good way of dealing with complex mazes that have uniform sizes.4 Advanced Work In Maze representation we say that it would be better to focus on graph. Just we have to traverse through the holes & exit the maze.'I'.'K':['L']. not where we go across fields. In DFS. It’s a searching where we go deep. Even we can use standard C with arrays or structs data structures to represent the graph. it just the matter of time to choose a good graph traverse algorithm from most common availability BFS or DFS. Each pixel color sets in the matrix by their row and column pixel index.'J']. BFS or DFS? When we compare BFS and DFS. there’s no exception to go for another. Assuming mazes are also given from RGB images where black lines set the walls and white cells set the path.3 Maze Solving Since we have the graph.'H':['D'. Here we are looking for search through hierarchical structure – Maze. 2. BFS searches siblings first while DFS searches for children first. . start (‘G’) and end (‘J’) points. thus DFS implemented using Stack and BFS using Queue data structures.'G':['D'.'H'].

. and so on & gives the shortest path possible. We can interactively produce maze solving path by coloring up the path we run in BFS. Each cell in the matrix has at least for adjacencies -up.value): if value == (255. BFS we use color code to describe with each node that it has been visited or not. Just changing the visited pixel value provides us the below solved maze. down. we get the down most elements that have recursive called. def isWhite(self. Then for each of those neighbor nodes in turn. We can simply use. But this circumstance avoids with BFS & even we can make some improvements to the code. Yes we proved that DFS is better algorithm to play with mazes.255. we have to again deal with BFS or DFS.255.0 Q 02 – SOLVING MAZE 6 When we are going to solve the maze from adjacency matrix. next & previous. But each sub-call we deal with adjacencies. It is because DFS uses recursive algorithm to move between its children. Running time is far worse than DFS linear time before. it inspects their neighbor nodes which were unvisited. If we go for down first. Here we can avoid that.255): return True The BFS begins at a root node and inspects all the neighboring nodes. But here DFS performs much worst result than BFS. our image pixel value to deal with this.2.

3. solve the sub-problems recursively. Illustrate appropriate stages/ states and the optimal-value function. The running time of Dynamic Programming is O(|V|+|E|). Divide-and-conquer algorithm is used when the overlapping problems are much smaller than the original problem.3 Why Dynamic Programming? Dynamic Programming is a method used for solving complex problems by breaking them into simpler sub-problems identical to divide-and-conquer algorithm. The problem will be divided into disjoint sub-problems. and then combine their solutions to solve the original problem.0 Q 01 – NEW MACHINE PROBLEM 7 3. As we make each choice. sub problems of the same from often arise. The sub-problems should not be independent in order to apply Dynamic Programming. . we can solve the problem by combining the solutions to sub problems. When devising an optimal solution based on dynamic programming.0 Q 01 – NEW MACHINE PROBLEM 3. but Dynamic Programming is used in much more complex problems.3. we have to make a set of choices at each end of the year. Thus we arrives at a position where given sub problem may arise from more than one partial set of choices. The number of sub-problems is exactly the number of vertices. This will reduce the running time of algorithms dramatically from exponential to polynomial. In order to arrive at an optimal solution. 3. so it will avoid re-computing the answer every time the sub-problem is encountered.2 Approach to Solution The company wants to minimize the cost over 5 year period.1 Problem Overview Devise an optimal solution based on dynamic programming for new machine problem. This method saves the answer of every sub-problem in a table after solving once. In the year 0 they are going to buy a machine & each year they have to decide whether the machine is being kept or traded.

1. it almost never works. To check for overlapping sub-problems we simply draw a recursion tree for the given problem.4 Optimal value Function Let the stages correspond to each year. t≠0. Let Ft(x) be the minimum cost incurred from time t to time 5. . Base cases: Since we have to trade machine in the end of 5 year F5(x)=-S[x] In the year 0 we buy a new machine F0(1)=N+M[1]+F1(0) In the range of 5 years and at most 3 years of age : 0 Keep existing machine at most 3 years : Ft(3)=N+M[0]+Ft+1(0) .3. but the control structure for filling the table is more like the recursive algorithm.0 Q 01 – NEW MACHINE PROBLEM 8 The general greedy strategy is look for the best first step. While this approach seems very natural. Dynamic Programming takes account of this fact and solves each sub-problem only once. The state is the age of the machine for that year. take it. The decisions are whether to keep the machine or trade it in for a new one. 3.2 Mostly in Dynamic Programming a bottom-up tabular approach is used. This is done with the use of a simple cut-and-paste argument. given the machine is x years old in time t. optimization problems that can be solved correctly by a greedy algorithm are very rare. • Overlapping Sub-problems – a recursive solution contains a “small” number of distinct sub-problems repeated many times. A table will be maintained with sub-problem solutions. Memoization is an alternative approach to Dynamic Programming that often offers the efficiency of the bottom-up approach while maintaining top-down strategy. The first step done in a Dynamic Programming solution is to check whether the problem exhibits optimal substructure. The elements of Dynamic Programming are: • Optimal Substructure – an optimal solution to a problem (instance) contains optimal solutions to sub-problems. and then continue.

Fxy(time+1. Ex: When it traverses F1(0).N+self. Then we can traverse two possible paths.Fxy(time+1. the left child continuously until it reaches the leaves.Matrix[time][age]==T and self.Matrix[time][age] 3.N+self.age): if self. it has ‘TRADE OR KEEP’ decision binds with it. We use a recursive algorithm where it traverses each tree level & make the path where current decision point occurs.Flag[time][age]='TRADE' else: T=self.M[0]+self.Matrix[time][age]=K=self.0) if age+1<len(self.Flag[time][age]='TRADE' else: self.3.y) .Matrix[time][age]=T=self.Fxy(time+1. since it has ‘KEEP’ decision then recursively we traverse F3(2).Flag[x][y]) return self.append(self.N+self.Matrix[time][age]==None: <.M[0]+self.Fxy(time+1.x. When ‘TRADE’ met.Matrix[time][age]=min(T.Flag[time][age]='TRADE' elif time==0: self.M[0]+self.S[age] self.Flag[time][age]='KEEP' return self. the right child.Overlaping subproblems avoided if(time>5 or age>2): return 0 if time==5: self.time) self.K) if(self.M[age+1] self.0) self.S[age]+self. When it traverses F2(1).Flag[x][y] else: if(self.Matrix[0]): K=self.dic[x].recursePath(x+1.Flag[time][age]='TRADE OR KEEP' elif(self.Matrix[time][age]==T): self.time.M[age+1]+self.Matrix[time][age]=T=self.0 Q 01 – NEW MACHINE PROBLEM 9 def Fxy(self. def recursePath(self.Matrix[time][age] else: return self.S[age]+self.Matrix[time][age]==K): self.age+1) else: K=self.Flag[x][y]=='TRADE OR KEEP'): self.Flag[time][age]='KEEP' elif time==3 and age==2: self.5 Optimal Solutions Optimal solutions can be achieved via drawing a decisions tree contains all possible paths & takes the minimum cost paths.y): if(x==5): self.

// This array should be entirely sorted.y+1) if(self. make change of n units using coins and we can check whether we can get optimal solution or not that simply means we can check whether we can change this units using minimum number of coins.i++){ if(amount>=coin[i]){ nOFc2=amount/coin[i]. By using the “Greedy algorithm” we can solve the question number four.recursePath(x+1.append(self.10.4.1 Greedy Algorithm Main process in greedy algorithm double coin[]={100. 4.0 Q 01 –COIN PROBLEM “Greedy algorithm” can be used to solve problems like coin change. -: Amount = 15 Coins = {10. count+=nOFc. By using the above algorithm we can calculate the number of coins which we can use to change that unit.length. e.2..Flag[x][y]) return self. amount%=coin[i]. scheduling problems.i<coin.dic[x].y) self.y+1) if(self. Runtime of this algorithm is O (n log n). Here we used two codes which we coded using Greedy algorithm and the Dynamic algorithm.!! for(int i=0. Question four contains a coin change problem.Flag[x][y]=='TRADE'): self. SOP("Number of "+coin[i]+" coin(s) : "+nOFc).Flag[x][y]=='KEEP'): self.1}. SOP("Amount of this step --> "+nOFc+"*"+coin[i]+" = "+nOFc*coin[i]).25. Here we provide the amount and the coins as inputs.0 Q 01 –COIN PROBLEM 10 self. 7. This algorithm checks the coins according to the descending order. nOFc=(int)nOFc2.recursePath(x+1.5.50. Through that we try to compare both algorithms. shortest path problems and activity selection problems.recursePath(x+1.Flag[x][y] 4. 1} .g.

25.length.50.10.j++){ if(i==1 & j<coin[i]){ table[i][j]=10000. So according to the above example we can say that we need 6 coins to change the amount 15.0 Q 01 –COIN PROBLEM 11 Include coin 10 = 15/10 1 Include coin 7 for remaining amount = (15. }else if(j<coin[i]){ table[i][j]=table[i-1][j].10*1 – 7*0)/1 5 According to the above illustration we can further illustrate that the amount 15 can be change by one coin from 10 and five coins from 5.length][amount+1].j<amount+1. By considering the above two examples which were solved using “Greedy Algorithm” and the “Dynamic Algorithm” we can clearly identify that By using the “Greedy Algorithm” we cannot find out optimal solution all the time because “Greedy algorithm” do not always yield optimal solutions.100}. But we cannot find the optimal solution all the time. but for many problems they do.2 Dynamic Algorithm Main process in dynamic algorithm int [] coin={0.10*1)/7 0 Include coin 1 for remaining amount = (15 . else table[i][j]=1+table[i][j-coin[i]].i<coin. for(int k=0. If the coins are spread out as mention in the question four we can find the optimal solution using “Greedy algorithm”.2.5.k++){ table[k][0]=0. In “Dynamic algorithm”.i++){ for(int j=1. int [][] table=new int[coin. }else{ if(table[i-1][j]<(1+table[i][j-coin[i]])) table[i][j]=table[i-1][j]. } for(int i=1.k<coin.4. }else if(i==1){ table[i][j]=1+(table[1][j-coin[1]]).length. . 4.1. problem divide into sub problems and then solve every sub problem and save the answer in a table after that find the optimal solution for the problem from the optimal solutions of the sub problems.

- MatchingUploaded byMohamed Kobeissi
- GCSE Mock PaperUploaded bysivashanth
- zozzleUploaded byMike Schiffman
- Assembly LineUploaded byHrvoje Bogeljic
- Dp IntroUploaded byZulqarnayn
- Data Structure and Algorithm List From Jami SirUploaded byS M Shamim শামীম
- 2002-10-17Uploaded byapi-168623254
- dfs and bfsUploaded byAbdul Azam Shaikh
- GraphsUploaded byRahulRoy
- final2Uploaded byJohn Wayne
- Edge Magic Total Labeling of PrismUploaded byBec Coronado
- Advance AlgorithmUploaded bypk
- DFS-QoS-CI2Uploaded byWin Winzky
- p4-freegrafUploaded byMariana Lescinschi
- Syllabus_Network_Economics.pdfUploaded byfarolnar7791
- SchedulingUploaded byZhichaoWang
- SyllabusUploaded byHala Alesaili
- GraphsUploaded byRajendranbehappy
- Combinatorial EnumerationUploaded byKiran Kumar Kuppa
- Blockchain Accelerates Insurance Transformation FsUploaded bythakornikita001.nt10
- Cs188 Lecture 2 and 3 -- Search (2PP)Uploaded byKanai Lomayani
- Hello WorldUploaded bySandeep Srikumar
- 03 Lab Igraph1Uploaded bySamuel Ramirez
- Assignment 1(1)Uploaded byPranav Soneji
- Introduction to Graph TheoryUploaded byLeslie Wu
- 05-Recursion_DynamicProgrammingUploaded byAnderson Dosantos
- Solutions ArmstrongUploaded byEmmanureva
- New England New York 68 Bus System Study ReportUploaded byViraj Viduranga Muthugala
- WBUT 5th SEMESTER SYLLABUS CSE 2012Uploaded byRitwick Halder
- 05703167Uploaded byprabhumalu

- General Guidelines+for+Conducting+InterviewsUploaded byAnie 蔡梦妮
- Verbal CommunicationUploaded byRamla Raheem
- attritionUploaded byphaneendraicfaipress
- Angelakis-2007-EEG APF Elderly CogUploaded bypsitati7656
- 15MA301_aug16Uploaded byS-Karthik
- Total Quality Management, BalancedUploaded byRadit Mursid
- Held and Hein Kitten CarouselUploaded byDua Ishaque
- Res DesignsUploaded byHimanshu Chitkara
- Sheldon Peck 2010. DapUploaded bykuzakutuza
- BscUploaded byjuanfra20
- ASSIGNMENT 3 - Research Report - All PartsUploaded byZordan
- Questionnaire succession planningUploaded byPrince Satish Reddy
- Essay 1 Comm Research (Autosaved)Uploaded byGayathiriDevi
- Shl Test Results ScoresUploaded byEdoardoMarangon
- Web PortalUploaded bycoolgiant
- 94093353Uploaded byno.name92
- Palinologi SurinameUploaded byUkky Martha Saputra
- Preventive FinalUploaded byChloe
- 18Uploaded byClaudia Eveline
- TSCI 2017 ReportUploaded byAnonymous haeqMIhs
- NumbersUploaded byTanyaradzwa Chimwendo
- The Pedantic 21st Century Engineering Student - Some ObservationsUploaded byb96er3
- Norwegian University of Science and TechnologyUploaded byAtif Awan
- 9781135650674_preview.pdfUploaded byUciha Hidayat
- KEY CONCEPTS OF CHILD AND ADOLESCENT.pptUploaded bykm lagang
- Innovation BuildingUploaded byEko Waluyo
- syllabusUploaded by32587412369
- THE ROLE OF SCHOOL-BASED SUPPORT AND COPING SKILLS IN THE DEVELOPMENT OF ANXIETY IN LGBTQ YOUNG ADULTSUploaded byJen Piccolo
- Knowledge Products and Services: Building a Stronger Knowledge InstitutionUploaded byIndependent Evaluation at Asian Development Bank
- TAMU 2011 Tower Overfill Hazard - A Program Approach to Re…Uploaded bywlmostia