User Tools

Site Tools


breadth-first_search_and_depth-first_search

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
breadth-first_search_and_depth-first_search [2016/05/24 00:30] dwallacebreadth-first_search_and_depth-first_search [2017/02/09 12:22] (current) dwallace
Line 1: Line 1:
 =====Introduction===== =====Introduction=====
  
-This tutorial serves as an introduction to path-planning and search algorithms. However, these topics do require prior knowledge of the methods used to program these algorithms. In order to understand these tutorials, you will need to be comfortable with C++, and especially the concepts associated with linked lists, stacks, and queues. An understanding of graph trees and how they are searched is also helpful for these tutorials.+This tutorial serves as an introduction to path-planning and search algorithms. However, these topics do require prior knowledge of the methods used to program these algorithms. In order to understand these tutorials, you will need to be comfortable with Cpp, and especially the concepts associated with linked lists, stacks, and queues. An understanding of graph trees and how they are searched is also helpful for these tutorials.
  
-If you want to learn C++ before reading these tutorials, there are a wealth of tutorials on the internet, and many will have different learning impact depending on personal preference. Here is one that I found helpful when learning the basics of C++: http://www.cplusplus.com/doc/tutorial/.+If you want to learn Cpp before reading these tutorials, there are a wealth of tutorials on the internet, and many will have different learning impact depending on personal preference. Here is one that I found helpful when learning the basics of Cpp: http://www.cplusplus.com/doc/tutorial/.
  
 To learn or refresh your knowledge of linked lists, here is a great tutorial for these concepts: http://www.cprogramming.com/tutorial/lesson15.html. To learn or refresh your knowledge of linked lists, here is a great tutorial for these concepts: http://www.cprogramming.com/tutorial/lesson15.html.
Line 18: Line 18:
 Breadth-First Search (BFS) is a searching algorithm that utilizes the concepts involved with the queue data structure. BFS works by expanding all successors to a node before moving onto analyzing any of those successors. This is known as a first-in, first-out (FIFO) approach. As the search goes through the nodes, it analyzes which nodes are successors, and adds those nodes to the queue as they are found. Then, the search goes back to the queue, and starts to dequeue the nodes in the order that they were added, analyzing those successors and adding them to the queue as well. This method of searching through a graph expands all nodes as it searches, and therefore it can be fairly inefficient if the goal is very far from the root node. However, tracing the path from root to goal is much easier using this search method. Breadth-First Search (BFS) is a searching algorithm that utilizes the concepts involved with the queue data structure. BFS works by expanding all successors to a node before moving onto analyzing any of those successors. This is known as a first-in, first-out (FIFO) approach. As the search goes through the nodes, it analyzes which nodes are successors, and adds those nodes to the queue as they are found. Then, the search goes back to the queue, and starts to dequeue the nodes in the order that they were added, analyzing those successors and adding them to the queue as well. This method of searching through a graph expands all nodes as it searches, and therefore it can be fairly inefficient if the goal is very far from the root node. However, tracing the path from root to goal is much easier using this search method.
  
-For a more visual overview of this searching method, reference the first-half of this tutorialhttp://www.pdf-archive.com/2016/05/24/bfsdfstutorial/.+For a more visual overview of this searching method, reference the first-half of {{dylanw:bfsdfstutorial.pdf|this document}}.
  
 The algorithm for BFS works like this: The algorithm for BFS works like this:
Line 35: Line 35:
  
 ===BFS Code (w/ comments)=== ===BFS Code (w/ comments)===
 +<file c++ BFS.cpp>
 +#include <iostream>
 +#include <ctime>
 +using namespace std;
  
-    #include <iostream> +struct node //the data structure for the nodes that are being explored 
-    #include <ctime> +
-    using namespace std; +    int data; 
-     +    node *next; 
-    struct node //the data structure for the nodes that are being explored +};
-    +
-        int data; +
-        node *next; +
-    }+
-     +
-    class Queue //the data structure for the queue that is being used to store the nodes that are being searched +
-    { +
-        private: +
-            node *front; +
-            node *rear;+
  
-        public: +class Queue //the data structure for the queue that is being used to store the nodes that are being searched 
-            Queue() +
-            +    private: 
-                front = NULL+        node *front; 
-                rear = NULL; +        node *rear;
-            }+
  
-            ~Queue() +    public: 
-            +        Queue() 
-                delete front; +        
-            }+            front = NULL
 +            rear = NULL; 
 +        }
  
-            void display() //displays the nodes stored within the queue+        ~Queue() 
 +        { 
 +            delete front; 
 +        } 
 + 
 +        void display() //displays the nodes stored within the queue 
 +        { 
 +            node *p = new node(); 
 +            p = front; 
 +            if(front == NULL) 
 +                cout << "\nNothing to display!" << endl; 
 + 
 +            else
             {             {
-                node *p = new node(); +                while(p != NULL)
-                = front; +
-                if(front == NULL) +
-                    cout << "\nNothing to display!" << endl; +
- +
-                else+
                 {                 {
-                    while(p != NULL) +                    cout << "\n" << p->data << endl; 
-                    { +                    p = p->next;
-                        cout << "\n" << p->data << endl; +
-                        p = p->next; +
-                    }+
                 }                 }
             }             }
 +        }
  
-            void enqueue(int indata) //adds a new node to the queue +        void enqueue(int indata) //adds a new node to the queue 
-            +        
-                node *temp = new node(); +            node *temp = new node(); 
-                temp->data = indata; +            temp->data = indata; 
-                temp->next = NULL; +            temp->next = NULL; 
-                if(front == NULL) +            if(front == NULL) 
-                    front = temp;+                front = temp;
  
-                else +            else 
-                    rear->next = temp;+                rear->next = temp;
  
-                rear = temp; +            rear = temp; 
-            }+        }
  
-            int dequeue() //removes a node from the queue and returns the value of that node+        int dequeue() //removes a node from the queue and returns the value of that node 
 +        { 
 +            node *temp = new node(); 
 +            int tempdata; 
 +            if(front == NULL) 
 +                cout << "\nQueue is empty!" << endl; 
 + 
 +            else
             {             {
-                node *temp = new node()+                temp = front
-                int tempdata; +                tempdata = temp->data
-                if(front == NULL) +                front = front->next; 
-                    cout << "\nQueue is empty!" << endl;+                delete temp; 
 +            }
  
-                else +            return tempdata; 
-                { +        }
-                    temp = front; +
-                    tempdata = temp->data; +
-                    front = front->next; +
-                    delete temp+
-                }+
  
-                return tempdata+        bool isEmpty() //returns whether the queue is empty or not 
-            }+        { 
 +            return (front == NULL)
 +        } 
 +};
  
-            bool isEmpty() //denotes whether the queue is empty or not +class Graph //the data structure for the graph that is to be searched through 
-            +
-                return (front == NULL)+    private: 
-            } +        int n//# of vertices in graph 
-    };+        int **A//stores the edge between two vertices
  
-    class Graph //the data structure for the graph that is to be searched through +    public: 
-    +        Graph(int size) //allows for variable creation of initial nodes 
-        private: +        
-            int n; //# of vertices in graph +            if(size < 2) 
-            int **A; //stores the edge between two vertices+                = 2;
  
-        public: +            else 
-            Graph(int size) //allows for variable creation of intital nodes +                n = size;
-            { +
-                if(size < 2) +
-                    n = 2;+
  
-                else +            A = new int*[n]; 
-                    n = size;+            for(int i = 0; i < n; i++) 
 +                A[i] new int[n];
  
-                A = new int*[n]+            for(int j = 0; j < n; j++) 
-                for(int = 0; < n; i++) +                for(int = 0; < n; k++) 
-                    A[i= new int[n];+                    A[j][k= 0; 
 +        }
  
-                for(int j = 0; j < n; j+++        ~Graph() 
-                    for(int = 0; < n; k++) +        { 
-                        A[j][k= 0; +            for(int = 0; < n; i++) 
-            }+                delete [] A[i];
  
-            ~Graph() +            delete [] A; 
-            { +        }
-                for(int i = 0; i < n; i++) +
-                    delete [] A[i];+
  
-                delete [] A+        bool isConnected(int u, int v) //returns whether the two nodes being checked are connected to each other in the graph 
-            }+        { 
 +            return (A[u-1][v-1] == 1)
 +        }
  
-            bool isConnected(int u, int v) //denotes is the two nodes being checked are connected to each other in the graph +        void addEdge(int u, int v) //adds a connection between the two given nodes 
-            +        
-                return (A[u-1][v-1] == 1)+            A[u-1][v-1] = A[v-1][u-1] = 1; 
-            }+        }
  
-            void addEdge(int u, int v) //adds a connection between the two given nodes +        void BFS(int s, int g) //the Breadth-First Search function for searching through the graph 
-            +        
-                A[u-1][v-1] = A[v-1][u-1] = 1+            Queue Q
-            }+            bool found = false; //denotes whether the goal node has been found
  
-            void BFS(int s, int g) //the Breadth-First Search function for searching through the graph +            bool *explored new bool[n+1]//stores explored vertices
-            { +
-                Queue Q; +
-                bool found false;+
  
-                bool *explored new bool[n+1]; //stores explored vertices+            for(int i = 1; i <= n; i++) //initializes all vertices as unexplored 
 +                explored[i] = false;
  
-                for(int i = 1; i <= n; i++) //initializes all vertices as unexplored +            Q.enqueue(s)//adds intial vertex 
-                    explored[i] = false;+            explored[s] = true; 
 +            cout << "BFS starting from vertex " << s << endl;
  
-                Q.enqueue(s); //adds intial vertex +            while(!Q.isEmpty() && !found) 
-                explored[s] true+            { 
-                cout << "BFS starting from vertex " << s << endl;+                int v Q.dequeue()
 +                cout << << " ";
  
-                while(!Q.isEmpty() && !found)+                if(v == g//stops the search after the goal node has been found
                 {                 {
-                    int v = Q.dequeue(); +                    cout << "\n\nGoal found."; 
-                    cout << v << " ";+                    found = true; 
 +                }
  
-                    if(v == g) //stop the search after the goal node has been found +                else 
-                    +                
-                        cout << "\n\nGoal found."; +                    for(int w = 1; w <n; w++)
-                        found = true; +
-                    } +
- +
-                    else+
                     {                     {
-                        for(int = 1; w <= n; w++)+                        if(isConnected(v, w) && !explored[w]//enqueues the nodes that are connected to each other, in a FIFO order
                         {                         {
-                            if(isConnected(v, w) && !explored[w]) //enqueues the nodes that are connected to each other, in a FIFO order +                            Q.enqueue(w); 
-                            { +                            explored[w] = true;
-                                Q.enqueue(w); +
-                                explored[w] = true; +
-                            }+
                         }                         }
                     }                     }
                 }                 }
- 
-                cout << endl; 
-                delete [] explored; 
             }             }
-    }; 
  
-    int main() +            cout << endl; 
-    { +            delete [] explored; 
-        Graph g(12);+        
 +};
  
-        g.addEdge(1, 2); +int main() 
-        g.addEdge(1, 3); +{ 
-        g.addEdge(2, 4); +    Graph g(12); //creates a graph with 12 nodes
-        g.addEdge(3, 4); +
-        g.addEdge(3, 6); +
-        g.addEdge(4, 7); +
-        g.addEdge(5, 6); +
-        g.addEdge(5, 7);+
  
-        clock_t t1+    g.addEdge(1, 2); //these edges can be changed and modified to make any graph 
-        t1 = clock();+    g.addEdge(1, 3); 
 +    g.addEdge(2, 4); 
 +    g.addEdge(3, 4); 
 +    g.addEdge(3, 6); 
 +    g.addEdge(4, 7); 
 +    g.addEdge(5, 6)
 +    g.addEdge(5, 7);
  
-        g.BFS(1, 3)+    clock_t t1
-        float diff (double)(clock() - t1)/CLOCKS_PER_SEC; +    t1 = clock();
-        cout << endl << "Time taken for BFS: " << diff << endl;+
  
-        return 0+    g.BFS(1, 3)//both tyhe root node and the goal node can be changed 
-    }+    float diff = (double)(clock() - t1)/CLOCKS_PER_SEC; //keeps track of the time taken for BFS 
 +    cout << endl << "Time taken for BFS: " << diff << endl;
  
 +    return 0;
 +}
 +</file>
 =====Depth-First Search===== =====Depth-First Search=====
  
Line 246: Line 246:
  
 ===DFS Code(w/ comments)=== ===DFS Code(w/ comments)===
-    #include <iostream> +<file c++ DFS.cpp> 
-    #include <ctime> +#include <iostream> 
-    #include <malloc.h> +#include <ctime> 
-    using namespace std;+#include <malloc.h> 
 +using namespace std;
  
-    struct node //the data structure fopr the nodes that are being explored +struct node //the data structure for the nodes that are being explored 
-    +
-        int data; +    int data; 
-        struct node *next; +    struct node *next; 
-    };+};
  
-    class stack //the data structure for the queue that is being used to store the nodes that are being searched +class stack //the data structure for the queue that is being used to store the nodes that are being searched through 
-    +
-        private: +    private: 
-            struct node *top;+        struct node *top;
  
-        public: +    public: 
-            stack()+        stack() 
 +        { 
 +            top = NULL; 
 +        } 
 + 
 +        void push(int indata) //pushes a node onto the top of the stack 
 +        { 
 +            node *p; 
 +            if((p=(node*)malloc(sizeof(node))) == NULL)
             {             {
-                top = NULL;+                cout << "Memory Exhausted"; 
 +                exit(0);
             }             }
  
-            void push(int indata) //pushes a node onto the stack+            p = new node; 
 +            p->data = indata
 +            p->next = NULL; 
 +            if(top != NULL)
             {             {
-                node *p; +                p->next = top
-                if((p=(node*)malloc(sizeof(node))) == NULL) +            } 
-                { +            top = p; 
-                    cout<<"Memory Exhausted"; +        }
-                    exit(0)+
-                }+
  
-                p = new node; +        int pop() //pops a node from the top of the stack 
-                p->data = indata+        { 
-                p->next = NULL+            struct node *temp
-                if(top != NULL) +            int value
-                { +            if(top == NULL) 
-                    p->next = top; +            
-                +                cout << "\nThe stack is Empty" << endl;
-                top = p;+
             }             }
  
-            int pop() //pops a node from the top of the stack+            else
             {             {
-                struct node *temp; +                temp = top
-                int value+                top = top->next
-                if(top =NULL) +                value temp->data; 
-                { +                delete temp; 
-                    cout << "\nThe stack is Empty" << endl+            } 
-                }+            return value
 +        }
  
-                else +        bool isEmpty() //returns whether the stack is empty 
-                +        
-                    temp = top; +            return (top == NULL)
-                    top = top->next; +        
-                    value temp->data+ 
-                    delete temp; +        void display() //displays the nodes and their order in the stack 
-                +        { 
-                return value; +            struct node *p = top;
-            }+
  
-            bool isEmpty() //denotes whether the stack is empty+            if(top == NULL)
             {             {
-                return (top == NULL);+                cout << "\nNothing to Display\n";
             }             }
  
-            void display() //displays the nodes and their order in the stack+            else
             {             {
-                struct node *p = top;+                cout << "\n The contents of stack\n";
  
-                if(top == NULL)+                while(p != NULL)
                 {                 {
-                    cout << "\nNothing to Display\n";+                    cout << p->data << endl; 
 +                    p = p->next;
                 }                 }
 +            }
 +        }
 +};
  
-                else +class Graph //the data structure for the graph that contains the nodes and the edges between them 
-                +
-                    cout << "\The contents of stack\n";+    private: 
 +        int n
 +        int **A;
  
-                    while(p != NULL+    public: 
-                    +        Graph(int size//allows for variable creation of graph size 
-                        cout << p->data << endl+        
-                        p = p->next; +            int i, j
-                    } +            if (size < 2) 
-                +                n = 2;
-            } +
-    };+
  
-    class Graph +            else 
-    { +                = size;
-        private: +
-            int n+
-            int **A;+
  
-        public: +            A = new int*[n];
-            Graph(int size) //allows for variable creation of graph sizes +
-            { +
-                int i, j; +
-                if (size < 2) +
-                    = 2;+
  
-                else +            for (i = 0; i < n; ++i) 
-                    n = size;+                A[i] new int[n];
  
-                A new int*[n];+            for (i 0; i < n; ++i) 
 +                for (j = 0; j < n; ++j) 
 +                    A[i][j] = 0; 
 +        }
  
-                for (i = 0; i < n; ++i) +        ~Graph() 
-                    A[i] = new int[n];+        { 
 +            for (int i = 0; i < n; ++i) 
 +            delete [] A[i]
 +            delete [] A; 
 +        }
  
-                for (i = 0; i < n; ++i+        bool isConnected(int x, int y//returns whether two nodes are connected to each other 
-                    for (j = 0; j < n; ++j) +        { 
-                        A[i][j] = 0+            return (A[x-1][y-1] == 1)
-            }+        }
  
-            ~Graph() +        void addEdge(int x, int y//adds an edge connecting the two given nodes 
-            +        
-                for (int i = 0; i < n; ++i) +           A[x-1][y-1] = A[y-1][x-1= 1
-                delete [] A[i]+        }
-                delete [] A+
-            }+
  
-            bool isConnected(int x, int y) //denotes whether two nodes are connected to each other +        void DFS(int x, int g//the function used for the Depth-First Search 
-            { +        { 
-                return (A[x-1][y-1] == 1); +            stack s; 
-            }+            bool *explored = new bool[n+1]; //stores explored nodes 
 +            bool found = false; //denotes whether the goal node has been found 
 +            int i; 
 +            for(i = 0; i <= n; i++) //initializes all nodes as unexplored 
 +                explored[i] = false; 
 +            s.push(x); //adds the initial node to the top of the stack 
 +            explored[x] = true;
  
-            void addEdge(int x, int y) //adds an edge connecting the two given nodes +            cout << "Depth first Search starting from vertex "; 
-            +            cout << << " : " << endl;
-                A[x-1][y-1] = A[y-1][x-1] = 1; +
-            }+
  
-            void DFS(int x, int g//the function for the Depth-First Search+            while(!s.isEmpty() && !found)
             {             {
-                stack s; +                int = s.pop(); 
-                bool *explored = new bool[n+1]; //stores explored nodes +                cout << k << " ";
-                bool found = false; +
-                int i; +
-                for(i 0; i <= n; i++) //initializes all nodes as not explored +
-                    explored[i] = false; +
-                s.push(x); //adds the initial node +
-                explored[x] = true;+
  
-                cout << "Depth first Search starting from vertex "; +                if(k == g) //stops the search after the goal is found 
-                cout << x << " : " << endl;+                { 
 +                    cout << "\n\nGoal found!"
 +                    found = true
 +                }
  
-                while(!s.isEmpty() && !found)+                else
                 {                 {
-                    int k = s.pop(); +                    for (i = n; i >= 0 ; i--) //pushes the nodes that are connected to each other, in LIFO order 
-                    cout << k << " "; +                        if(isConnected(k, i) && !explored[i]) 
- +                        
-                    if(k == g) //stops the search after the goal node has been found +                            s.push(i); 
-                    { +                            explored[i] = true; 
-                        cout << "\n\nGoal found!"; +                        }
-                        found = true; +
-                    } +
- +
-                    else +
-                    { +
-                        for (i = n; i >= 0 ; i--) //push the nodes that are connected to each other, in LILO order +
-                            if(isConnected(k, i) && !explored[i]) +
-                            +
-                                s.push(i); +
-                                explored[i] = true; +
-                            } +
-                    }+
                 }                 }
-                cout << endl; 
-                delete [] explored; 
             }             }
 +            cout << endl;
 +            delete [] explored;
 +        }
  
-    };+};
  
-    int main() +int main() 
-    +
-        Graph g(8); +    Graph g(8); //creates a graph with 8 nodes 
-        g.addEdge(1, 2); +    g.addEdge(1, 2); //adds edges between nodes (this is modular and can be changed) 
-        g.addEdge(1, 3); +    g.addEdge(1, 3); 
-        g.addEdge(1, 4); +    g.addEdge(1, 4); 
-        g.addEdge(2, 5); +    g.addEdge(2, 5); 
-        g.addEdge(2, 6); +    g.addEdge(2, 6); 
-        g.addEdge(4, 7); +    g.addEdge(4, 7); 
-        g.addEdge(4, 8);+    g.addEdge(4, 8);
  
-        clock_t t1; +    clock_t t1; 
-        t1 = clock();+    t1 = clock();
  
-        g.DFS(1, 4);+    g.DFS(1, 4); //both the root5 node and the goal node can be adjusted
  
-        float diff = (double)(clock() - t1)/CLOCKS_PER_SEC; +    float diff = (double)(clock() - t1)/CLOCKS_PER_SEC; //keeps track of the time taken to execute the search 
-        cout << endl << "Time taken for DFS: " << diff << endl;+    cout << endl << "Time taken for DFS: " << diff << endl;
  
-        return 0; +    return 0; 
-    }+} 
 +</file>
  
-=====Conclusion=====+=====Final Words=====
  
 Both Breadth-First Search and Depth-First Search are very important algorithms for searching through graphs, and are especially useful in implementing path planning on autonomous systems. They may not be the fastest searching algorithms, however they are very integral to the modern understanding of path planning and searching through large sets of data. For information on implementing these algorithms, see the implementation page for BFS and DFS under the Path Planning section of the wiki. Both Breadth-First Search and Depth-First Search are very important algorithms for searching through graphs, and are especially useful in implementing path planning on autonomous systems. They may not be the fastest searching algorithms, however they are very integral to the modern understanding of path planning and searching through large sets of data. For information on implementing these algorithms, see the implementation page for BFS and DFS under the Path Planning section of the wiki.
  
breadth-first_search_and_depth-first_search.1464075044.txt.gz · Last modified: 2016/05/24 00:30 by dwallace