This action might not be possible to undo. Are you sure you want to continue?

1. bfs uses queue implementation ie.FIFO dfs uses stack implementation ie. LIFO 2. dfs is faster than bfs 3. dfs requires less memory than bfs 4. dfs are used to perform recursive procedures. BFS CODE IN C: Code:

/* prog. on bfs */ #include<stdio.h> #include<stdlib.h> #define SIZE 10 #define T 1 #define F 0 #define NULL 0 struct edge { int terminal; struct edge *next; }; struct vertex { int visit; int vertex_no; char info; int path_lenth; struct edge *edge_ptr; }; struct q { int info; struct q *next; }; void table(int,int matrix[SIZE][SIZE],struct vertex vert[SIZE]); struct edge *insert_vertex(int,struct edge *); void bfs(int ,int *dist,struct vertex vert[SIZE]); void output(int,int a[SIZE][SIZE]); void input(int,int a[SIZE][SIZE]); struct q *insert_queue(int vertex_no,struct q *first); struct q *delet_queue(int *vertex_no,struct q *first); struct edge *insert_vertex(int vertex_no,struct edge *first) { struct edge *new1,*current ; new1=(struct edge*)malloc(sizeof(struct edge)); new1->terminal=vertex_no;

for(current=first.current=current->next).new1->next=NULL.edge_ptr=NULL.struct vertex vert[SIZE]) { int i.struct vertex vert[SIZE]) { struct q *queue=NULL. struct edge *link.edge_ptr.link.i++) { vert[i].*current.queue). for(current=first. for(link=vert[index].current->next. vert[i]. if(!first) return new1.current=current->next). queue=insert_queue(index. } void bfs(int index. first=first->next.struct q *first) { struct q *new1. vert[i].j. vert[i].current->next.visit=F.j++) if(matrix[i][j]>0) vert[i].struct q *first) { struct q *previous. *vertex_no=first->info. return first. return first.path_lenth=0. vert[index]. current->next=new1.vert[i]. new1=(struct q*)malloc(sizeof(struct q)).edge_ptr). new1->info=vertex_no. for(i=0.int *dist.visit=T. if(!first) return new1. vert[i].visit==F) . free(previous).i<vertex_num. current->next=new1.info='A'+i.link=link->next) if(vert[link->terminal]. } void table(int vertex_num. while(queue) { queue=delet_queue(&index.i++) for(j=0.edge_ptr=insert_vertex(j. return first. new1->next=NULL. } struct q *delet_queue(int *vertex_no.vertex_no=i+1.j<vertex_num. if(!first) return NULL.int matrix[SIZE][SIZE]. } for(i=0. } struct q *insert_queue(int vertex_no.queue).i<vertex_num.

j++) scanf("%d". printf("\ninput the number of vertices in graph:").i++) { printf("\n%c\t\t%d".i<number.a[i][j]).j++) printf("%d\t".list=list->next) { printf(" ").info. } } getch().i<number.&dist. printf("\ninput the strating vertex 0-%d:". queue=insert_queue(link->terminal. output(number.path_lenth=vert[index]. table(number.list.edge_ptr.i++) { for(j=0.&index). } . } } void main() { int i. } } } void input(int number.j. clrscr().vert[i].a[SIZE][SIZE].vert). printf("\n").&a[i][j]).vert[index]. scanf("%d". input(number.&number).number. } } void output(int number. putchar(list->terminal+'A').path_lenth).int a[SIZE][SIZE]) { int i.info). printf("\n adjacency matrix is:\n"). for(list=vert[i]. printf("\n path lenth of the vertex %c". vert[link->terminal].j<number. for(i=0.a.j.i++) { for(j=0.number-1).path_lenth+1.a). for(i=0. dist=0. printf("\n").queue).j<number.i<number.index. scanf("%d". struct vertex vert[SIZE].vert). printf("\n vertex length vertex complexity\n"). printf("input the adjacency matrix is:\n"). bfs(index.int a[SIZE][SIZE]) { int i.{ vert[link->terminal]. for(i=0.vert[i].a).visit=T.dist. struct edge *list.

}.h> #define SIZE 10 #define T 1 #define F 0 #define NULL 0 struct edge { int terminal. new1->terminal=vertex_no.int a[SIZE][SIZE]). void input(int. new1->next=NULL. on dfs */ #include<stdio.Algorithm for DFS DFS () { Initialize stack.struct vertex vert[SIZE]). Push all the neighbors of the vertex into stack . While (stack is not empty) { Pop an item from the stack and store it into vertex. void output(int. char info.int *dist. .struct vertex vert[SIZE]). Set visited flag of the vertex is equals to true.h> #include<stdlib. if(!first) return new1.struct edge *first) { struct edge *new1. void dfs(int . struct edge *insert_vertex(int.int a[SIZE][SIZE]). If (visited flag of vertex is false) { Visit vertex.int matrix[SIZE][SIZE]. Push the root vertex into stack. struct edge *edge_ptr. new1=(struct edge*)malloc(sizeof(struct edge)).*current . struct vertex { int visit. struct edge *insert_vertex(int vertex_no.struct edge *). int path_lenth. }. int vertex_no. void table(int. struct edge *next. } } DFS CODE IN C: Code: /* prog.

vert[i].j<number.current->next.info='A'+i.j++) if(matrix[i][j]>0) vert[i]. } for(i=0.j.edge_ptr=insert_vertex(j.struct vertex vert[SIZE]) { struct edge *link. for(i=0.i<number.} void table(int vertex_num.edge_ptr). } } void output(int number. struct vertex vert[SIZE]. printf("input the adjacency matrix is:\n"). printf("\n").j++) printf("%d\t".dist.visit=T.struct vertex vert[SIZE]) { int i.path_lenth=0. vert[index]. printf("\n adjacency matrix is:\n").vert). } void input(int number.a[i][j]).i++) { for(j=0.j++) scanf("%d".vert[i].visit=F.int a[SIZE][SIZE]) { int i.link.a[SIZE][SIZE].int *dist.i<vertex_num. for(i=0. vert[index].i<number.path_lenth= *dist.j. for(current=first. } } void main() { int i. current->next=new1. printf("\n").i++) for(j=0. .edge_ptr.dist. vert[i].current=current->next). for(link=vert[index].index.vertex_no=i+1. *dist+=1. for(i=0. return first.i<vertex_num.link=link->next) if(vert[link->terminal]. vert[i].edge_ptr=NULL.i++) { vert[i].j<number.int a[SIZE][SIZE]) { int i. vert[i].number.&a[i][j]).visit==F) dfs(link->terminal.i++) { for(j=0.j.int matrix[SIZE][SIZE]. } void dfs(int index.j<vertex_num.

number-1). scanf("%d".vert[i].list=list->next) { printf(" ").path_lenth). } } getch().edge_ptr. table(number. printf("\ninput the strating vertex 0-%d:".i<number.a). scanf("%d". printf("\nvertex lenth vertex complexity\n"). for(list=vert[i].info). for(i=0.vert[i].list. output(number.vert). Breadth-first search Breadth-first search Order in which the nodes are expanded • .&index).i++) { printf("\n%c\t\t%d".a). dist=0.a. printf("\ninput the number of vertices in graph:"). dfs(index.vert).&number). putchar(list->terminal+'A').info. input(number.&dist. printf("\npath lenth of thevertex %c".vert[index]. clrscr().} struct edge *list.

From the standpoint of the algorithm. o If the element sought is found in this node. . First Out) queue. breadth-first search (BFS) is a graph search algorithm that begins at the root node and explores all the neighboring nodes. It does not use a heuristic algorithm.e. until it finds the goal. Dequeue a node and examine it. it exhaustively searches the entire graph or sequence without considering the goal until it finds it. all child nodes obtained by expanding a node are added to a FIFO (i. and so on. • How it works BFS is an uninformed search method that aims to expand and examine all nodes of a graph or combination of sequences by systematically searching through every solution.. Then for each of those nearest nodes. In typical implementations. it explores their unexplored neighbor nodes. quit the search and return a result. 2. nodes that have not yet been examined for their neighbors are placed in some container (such as a queue or linked list) called "open" and then once examined are placed in the container "closed". In other words. First In. An example map of Germany with some connections between cities The breadth-first tree obtained Animated example of a when running BFS on the given breadth-first search map and starting in Frankfurt Algorithm (informal) 1.• In graph theory. Enqueue the root node.

every node on the graph has been examined – quit the search and return "not found". 4. repeat from Step 2. Since it is exponential in the depth of the graph.source): 2 create a queue Q 3 enqueue source onto Q 4 mark source 5 while Q is not empty: 6 dequeue an item from Q into v 7 for each edge e incident on v in Graph: 8 let w be the other end of e 9 if w is not marked: 10 mark w 11 enqueue w onto Q [edit] Features [edit] Space complexity Since all of the nodes of a level must be saved until their child nodes in the next level have been generated. . o Note: Using a stack instead of a queue would turn this algorithm into a depth-first search. breadth-first search is often impractical for large problems on systems with bounded space.Otherwise enqueue any successors (the direct child nodes) that have not yet been discovered. the space complexity can also be expressed as O( | V | ) where | V | is the cardinality of the set of vertices. the space complexity is proportional to the number of nodes at the deepest level. Time complexity Since in the worst case breadth-first search has to consider all paths to all possible nodes the time complexity of breadth-first search is which is O(bd). If the queue is empty. and additional data structures are used to determine which vertices have already been added to the queue. If the queue is not empty. O(bd). When the number of vertices in the graph is known ahead of time. Given a branching factor b and graph depth d the asymptotic space complexity is the number of nodes at the deepest level. The time complexity can also be expressed as O( | E | + | V | ) since every vertex and every edge will be explored in the worst case. 3. Pseudocode 1 procedure BFS(Graph. In the worst case the graph has a depth of 1 and all vertices must be stored.

If the graph is a weighted graph. and therefore all step costs are equal. breadth-first search will eventually find it after expanding all shallower nodes (provided that the branching factor b is finite). Cheney's algorithm Finding the shortest path between two nodes u and v Testing a graph for bipartiteness (Reverse) Cuthill–McKee mesh numbering Ford–Fulkerson method for computing the maximum flow in a flow network Serialization/Deserialization of a binary tree vs serialization in sorted order. This makes a breadth-first search sample of a graph very difficult to interpret. This problem is solved by improving breadth-first search to uniform-cost search which considers the path costs. breadth-first search is optimal. This means that if there is a solution. and therefore has costs associated with each step. For example.[2] [edit] Applications Breadth-first search can be used to solve many problems in graph theory. Nevertheless. if the graph is infinite and there is no solution breadth-first search will diverge. However. breadth-first search will find it regardless of the kind of graph. a goal next to the start does not have to be the cheapest goal available. [edit] Bias towards nodes of high degree It has been empirically observed (and analytically shown for random graphs) that incomplete breadth-first search is biased towards nodes of high degree.[1] Optimality For unit-step cost. for example: • • • • • • • Finding all nodes within one connected component Copying Collection. . In general breadth-first search is not optimal since it always returns the result with the fewest edges between the start node and the goal node.Completeness Breadth-first search is complete. breadth-first search will find the nearest and the best solution. Proof of completeness If the shallowest goal node is at some finite depth say d. allows the tree to be re-constructed in an efficient manner. a breadthfirst sample of 1 million nodes in Facebook (less than 1% of the entire graph) overestimates the average node degree by 240%. if the graph is not weighted.

iterative deepening depth-first search applies DFS repeatedly with a sequence of increasing limits. the graph to be searched is often either too large to visit in its entirety or even infinite. When an appropriate depth limit is not known a priori. Therefore. For applications of DFS to search problems in artificial intelligence. DFS also lends itself much better to heuristic methods of choosing a likely-looking branch. For such applications. all freshly expanded nodes are added to a stack for exploration. and takes time O(|V| + |E|). or graph. or until it hits a node that has no children. the time and space bounds are the same as for breadth-first search and the choice of which of these two algorithms to use depends less on their complexity and more on the different properties of the vertex orderings the two algorithms produce. returning to the most recent node it hasn't finished exploring. DFS is typically used to traverse an entire graph. In a non-recursive implementation. DFS is an uninformed search that progresses by expanding the first child node of the search tree that appears and thus going deeper and deeper until a goal node is found. Then the search backtracks.Depth-first search Depth-first search (DFS) is an algorithm for traversing or searching a tree. Properties The time and space analysis of DFS differs according to its application area. the search is only performed to a limited depth. Formal definition Formally. One starts at the root (selecting some node as the root in the graph case) and explores as far as possible along each branch before backtracking. tree structure. in this setting. . iterative deepening increases the running time by only a constant factor over the case in which the correct depth limit is known due to the geometric growth of the number of nodes per level. In these applications it also uses space O(|V|) in the worst case to store the stack of vertices on the current search path as well as the set of already-visited vertices. in the artificial intelligence mode of analysis. In this case. with a branching factor greater than one. the time is still linear in the number of expanded vertices and edges (although this number is not the same as the size of the entire graph because some vertices may be searched more than once and others not at all) but the space complexity of this variant of DFS is only proportional to the depth limit. linear in the size of the graph. and DFS may suffer from non-termination when the length of a path in the search tree is infinite. however. much smaller than the space needed for searching to the same depth using breadth-first search. and due to limited memory availability one typically does not use data structures that keep track of the set of all previously visited vertices. In theoretical computer science. Thus.

will visit the nodes in the following order: A. which point from a node of the tree to one of its descendants. Performing the same search without remembering previously visited nodes results in visiting nodes in the order A. D. . F. E. F. E. E cycle and never reaching C or G. Iterative deepening is one technique to avoid this infinite loop and would reach all nodes. D. caught in the A. back edges. and cross edges. E. B. It can be shown that if the original graph is undirected then all of its edges are tree edges or back edges. are classified separately from forward edges. C. forever. G. B. which point from a node to one of its ancestors. a structure with important applications in graph theory. A. F. B. D. B. D. the edges of the original graph can be divided into three classes: forward edges. F. Based on this spanning tree. Output of a depth-first search The four types of edges defined by a spanning tree The most natural result of a depth first search of a graph (if it is considered as a function rather than a procedure) is a spanning tree of the vertices reached during the search. Sometimes tree edges. assuming that the left edges in the shown graph are chosen before right edges. which do neither. etc. and assuming the search remembers previously-visited nodes and will not repeat them (since this is a small graph).Example For the following graph: a depth-first search starting at A. The edges traversed in this search form a Trémaux tree. edges which belong to the spanning tree itself.

A postordering is a list of the vertices in the order that they were last visited by the algorithm.e. A reverse postordering is the reverse of a postordering. This is a compact and natural way of describing the progress of the search. When searching a tree.Vertex orderings It is also possible to use the depth-first search to linearly order the vertices of the original graph (or tree). reverse postordering is the same as preordering. a list of the vertices in the opposite order of their last visit. This ordering is also useful in control flow analysis as it often represents a natural linearization of the control flow. There are three common ways of doing this: • A preordering is a list of the vertices in the order that they were first visited by the depth-first search algorithm. are included here (even if it is found to have none). to check if it has still unvisited neighbours. when searching the directed graph • • if (A) then { B } else { C beginning at node A. Note that repeat visits in the form of backtracking to a node. i. as was done earlier in this article. Reverse postordering produces a topological sorting of any directed acyclic graph. one visits the nodes in sequence. Thus the possible preorderings are A B D C and A C D B (order by node's leftmost occurrence in above list). or A C D C A B A (depending upon whether the algorithm chooses to visit B or C first). For example. to produce lists either A B D B A C A. A preordering of an expression tree is the expression in Polish notation. A postordering of an expression tree is the expression in reverse Polish notation. but in general they are different when searching a graph. while the possible reverse postorderings are A C B D and A B C D (order by node's rightmost occurrence in above list). The graph above might represent the flow of control in a code fragment like .

e) 6 if vertex w is unexplored then 7 label e as a discovery edge 8 recursively call DFS(G.opposite(v. Finding 2-(edge or vertex)-connected components. Topological sorting.incidentEdges(v) do 4 if edge e is unexplored then 5 w ← G. Finding strongly connected components.w) 9 else 10 label e as a back edge Applications Randomized algorithm similar to depth-first search used in generating a maze. but not natural to use the order A B D C or A C D B. Pseudocode Input: A graph G and a vertex v of G Output: A labeling of the edges in the connected component of v as discovery edges and back edges 1 procedure DFS(G. .} D and it is natural to consider this code in the order A B C D or A C B D. Algorithms that use depth-first search as a building block include: • • • • Finding connected components.v): 2 label v as explored 3 for all edges e in G.

) Maze generation may use a randomized depth-first search.• • • • Planarity Testing[citation needed] Solving puzzles with only one solution. Finding biconnectivity in graphs. (DFS can be adapted to find all solutions to a maze by only including nodes on the current path in the visited set. such as mazes. .

Sign up to vote on this title

UsefulNot useful- BFS DFS
- Display Devices
- AI Previous Years Question Papers Solved by Suresh S Koppal
- 6
- Differences Between C,C++,JAVA
- Unix & Shell Programming Lab Manual
- Graphs 1
- Graphs
- C,C++ Library
- Source Code for Data Structures and Algorithm Analysis in c
- C Lab Programs
- handbookdemo
- ALGORITHMS DESIGN TECHNIQUES AND ANALYSIS
- Data Stuctures Lab Manual
- Introduction to the Design & Analysis of Algorithms 2ND Edition by Anany Levitin
- 25422733 C Programming and Data Structures Lab Manual
- C++ Network Programming Vol 1
- C#
- Data Structr
- Discrete Syllabus
- Unit5_lecture1.pdf
- 12-graph
- Finite State Automata
- Lec9_MST
- 07 Reduced
- Problems Complete for Symmetric Log Space.ps
- DataStructure - Graphs
- Handout Presentation 7-02-13 Graph Drawing
- Graph
- 12 Graphs Post3up
- DFS and BFS