Вы находитесь на странице: 1из 10

UNIVERSITY OF PORTHARCOURT

ASSIGNMENTS ON IMPLEMENTATION OF BREADTH FIRST, DEPTH FIRST, HILL TOP & LEAST COST SEARCH ALGORTIHMS

SUBMITTED BY: ANYAMA OSCAR UZOMA APP. N0.: APPL/MSC/2012/COMP/108

LECTURER NAME: PROF. NWACHUKWU

DATE: 15TH MAY, 2013

IN PARTIAL FULFILLMENT OF THE AWARD OF A MASTERS DEGREE IN THE DEPARTMENT OF COMPUTER SCIENCE. DEPTH-FIRST SEARCH
A depth first search (DFS) visits all the vertices in a graph. When choosing which edge to explore next, this algorithm always chooses to go ``deeper'' into the graph. That is, it will pick the next adjacent unvisited vertex until reaching a vertex that has no unvisited adjacent vertices. The algorithm will then backtrack to the previous vertex and continue along any as-yet unexplored edges from that vertex. After DFS has visited all the reachable vertices from a particular source vertex, it chooses one of the remaining undiscovered vertices and continues the search

DEPTH FIRST SEARCH IMPLEMENTATION #include<iostream> #include<string.h> #include<math.h> using namespace std; int v,edge,c,b,adj[100][100],dfstime=0,x,y,i;

struct vertex { char colour[6]; int p; int f,d,key,small; }a[100]; void dfs_visit(vertex *g,int u) { dfstime=dfstime+1; g[u].d=dfstime; g[u].small=dfstime; strcpy(g[u].colour,"gray"); for(int j=1;j<=v;j++) { if (adj[u][j]==1) { if(!strcmp(g[j].colour,"white")) { g[j].p=u;

dfs_visit(g,j); if(!((g[j].small)<=g[u].d)) cout<<"BRIDGE : "<<g[j].key<<" "<<g[u].key<<"\n"; else g[u].small=g[j].small;} else { if(g[u].p!=j) if(g[j].d<g[u].small) g[u].small=g[j].small;}} else continue; } strcpy(g[u].colour,"black"); dfstime+=1; g[u].f=dfstime; } void dfs(vertex *a) { for(i=1;i<=v;i++) { strcpy(a[i].colour,"white"); a[i].p=0;} dfstime=0; for(i=1;i<=v;i++) { if (!strcmp(a[i].colour,"white")) dfs_visit(a,i);}} int main() { cout<<"ENTER NO: OF VERTICES\n"; cin>>v; cout<<"Enter no: of edges\n"; cin>>edge; cout<<"enter edges as pair of vertices"; for(int k=1;k<=edge;k++) { cin>>c>>b; adj[c][b]=1; adj[b][c]=1; } cout<<"ENTER THE VERTICES\n"; for(int k=1;k<=v;k++) cin>>a[k].key; dfs(a); cout<<"\nVertix\tStart Time\tFinishing Time\tColour"; for(i=1;i<=v;i++) cout<<"\n"<<a[i].key<<"\t"<<a[i].d<<"\t "<<a[i].f<<"\t "<<a[i].colour;

return 0; }

OUTPUT
SCREEN SHOTS

BREADTH-FIRST SEARCH
Breadth-first search is a traversal through a graph that touches all of the vertices reachable from a particular source vertex. In addition, the order of the traversal is such that the algorithm will explore all of the neighbors of a vertex before proceeding on to the neighbors of its neighbors. One way to think of breadth-first search is that it expands like a wave emanating from a stone dropped into a pool of water. Vertices in the same ``wave'' are the same distance from the source vertex. A vertex is discovered the first time it is encountered by the algorithm. A vertex is finished after all of its neighbors are explored.
BREADTH FIRST SEARCH IMPLEMENTATION #include <iostream> #include <ctime> using namespace std; struct node { int info; node *next; }; class Queue { private: node *front; node *rear; public: Queue(); ~Queue(); bool isEmpty();

void enqueue(int); int dequeue(); void display(); }; void Queue::display(){ node *p = new node; p = front; if(front == NULL){ cout<<"\nNothing to Display\n"; }else{ while(p!=NULL){ cout<<endl<<p->info; p = p->next; } } } Queue::Queue() { front = NULL; rear = NULL; } Queue::~Queue() { delete front; } void Queue::enqueue(int data) { node *temp = new node(); temp->info = data; temp->next = NULL; if(front == NULL){ front = temp; }else{ rear->next = temp; } rear = temp; } int Queue::dequeue() { node *temp = new node(); int value; if(front == NULL){ cout<<"\nQueue is Emtpty\n"; }else{ temp = front; value = temp->info; front = front->next; delete temp; } return value; } bool Queue::isEmpty() { return (front == NULL); } class Graph { private: int n; int **A; public:

Graph(int size = 2); ~Graph(); bool isConnected(int, int); void addEdge(int x, int y); void BFS(int , int); }; Graph::Graph(int size) { int i, j; if (size < 2) n = 2; else n = size; A = new int*[n]; for (i = 0; i < n; ++i) A[i] = new int[n]; for (i = 0; i < n; ++i) for (j = 0; j < n; ++j) A[i][j] = 0; } Graph::~Graph() { for (int i = 0; i < n; ++i) delete [] A[i]; delete [] A; } bool Graph::isConnected(int x, int y) { return (A[x-1][y-1] == 1); } void Graph::addEdge(int x, int y) { A[x-1][y-1] = A[y-1][x-1] = 1; } void Graph::BFS(int x, int required) { Queue Q; bool *visited = new bool[n+1]; int i; for (i = 1; i <= n; ++i) visited[i] = false; Q.enqueue(x); if(x == required) return; visited[x] = true; cout << "Breadth first Search starting from vertex "; cout << x << " : " << endl; while (!Q.isEmpty()) { int k = Q.dequeue(); if(k == required){ cout<<" FOUND HERE "; continue; } cout << k << " "; for (i = 1; i <= n; ++i) if (isConnected(k, i) && !visited[i]) { Q.enqueue(i); visited[i] = true; } } cout << endl; delete [] visited; }

int main() { Graph g(12); g.addEdge(1, 2); 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); clock_t t1; t1 = clock(); g.BFS(1, 15); float diff = (double)(clock() - t1)/CLOCKS_PER_SEC ; cout <<endl<< "The time taken for Breadth first search: "<< diff << endl; }

HILL CLIMBING SEARCH

/* * HillClimbing.java * * $LastChangedDate$ * $LastChangedRevision$ * Vicente J. Ferrer Dalmau * < vicente@jdalmau.es > * * Implementation of the Hill Climbing algorithm (simple version). */ package travelingsalesman; import java.util.ArrayList; /** * */ public class HillClimbing { RoutesMatrix distances; int sourceCity; String result = new String(); ArrayList followedRoute; int nodes = 0; int routeCost = 0; int HEURISTICCONSTANT = 15;

/** * Gets the heuristic value for a given depth * The level 0 has the maximum value. */ private int getHeuristicValue (int level) { return HEURISTICCONSTANT * (distances.getCitiesCount() - level); } /** Creates a new instance of HillClimbing */ public HillClimbing(RoutesMatrix matrix, int sourceCity) { distances = matrix; this.sourceCity = sourceCity; } /** * executes the algorithm */ public String execute () { followedRoute = new ArrayList(); followedRoute.add(sourceCity); nodes++; result = "HILL CLIMBING SEARCH\n\n"; long startTime = System.currentTimeMillis(); search(sourceCity); long endTime = System.currentTimeMillis(); result += "\nBetter solution: "+followedRoute.toString() + "// Cost: "+routeCost+"\n"; result += "Visited Nodes: "+nodes+"\n"; result += "Elapsed Time: "+(endTime-startTime)+" ms\n"; return result; } /** * @param from node where we start the search. */ public void search (int from) { int currentTown = from; while (nodes != distances.getCitiesCount()) { // choose the closest town int lowestDistance = Integer.MAX_VALUE; int chosen = -1; for (int i=0; i < distances.getCitiesCount(); i++) { if (!followedRoute.contains(i)) { int tempDistance = routeCost + getHeuristicValue(nodes-1); // f = g + h if (tempDistance < lowestDistance) { lowestDistance = tempDistance;

chosen = i; } } } routeCost += distances.getCost(currentTown, chosen); followedRoute.add(chosen); currentTown = chosen; nodes++; } // add the last town routeCost += distances.getCost(currentTown, sourceCity); followedRoute.add(sourceCity); nodes++; } }

Вам также может понравиться