![]() |
|
|
#1 |
|
Habitual
![]() Fecha de Ingreso: febrero-2005
Amigos 0
Mensajes: 205
Gracias: 0
Agradecido 4 veces en 3 mensajes.
|
Hola...
nececito un codec de una implementacion del algoritmo de dijkstra "ruta mas corta" une ejmplo: ya tengo mis nodos unidos con arcos solo em falta agregarle el peso del arco..nececito un ejemplo de dikstra para implementarselo.. dejo mi codec.. /*****************************************/ #include<iostream.h> #include<conio.h> //forward declaration of the class vertex //needed to reslove cyclic dependency between the classes vertex and Edge //declaracion adelantada de la clase vertex class Vertex; class Edge{ public: Edge(Vertex *, Edge *); ~Edge(); Vertex *getEnd(); void print(); Edge *getNext(); private: Vertex *end; //pointer to the end of the edge//puntero al fin del arco Edge *next; //pointer to the next edege in the list of edges associated //with the vertex //puntero al sigiente arco de la lista de arcos asociados con el vertice }; class Vertex{ public: Vertex(char, Vertex *); ~Vertex(); char getData(); void printEdges(); void printGraph(); void connectTo(Vertex *); Vertex *getNext(); Edge *getFirstEdge(); void ChangeFirstEdge(Edge *newEdge){edges=newEdge;} void ChangeStatus(int value){status=value;} int getStatus(){return status;} private: char data; //stores data of the vertex//almacena data en el vertice Edge *edges; //pointer to the list of outcoming edges of the vertex //puntero para la lista de puntero que vienen de fuera del el vertice Vertex *next; //pointer to the next vertex in the graph //puntero al siguiente vertice en el grafo int status; }; //methods of class Vertex //metodos de la clase vertice //Constructor: creates a vertex with data theData that points to the next //vertex nextVert and has no outcoming edges //constructor: crea un vertice con el dato theData,nextvert señala al siguiente vertice //y no tiene arcos que vienen de afuera Vertex::Vertex(char theData, Vertex *nextVert){ data=theData; next=nextVert; edges=0; //no edges//no arcos status=0; } //Destructor: deletes the outcoming edges (the edge destructor calls //destructor for the next edge) and calls destructor for the next vertex //of the graph //destructor elimina los arcos que viene de fuera //(el destructor del arco llama al destructor para el siguienet arco) y llama //al destructor para el siguiente vertice en el arco Vertex::~Vertex(){ delete next; delete edges; } //return the data of the vextex //regtorna el dato del vertice char Vertex::getData(){ return data; } //prints all the edges of the vertex by calling the print method //of the first edge //imprime todos los arcos de el vertice llamando al metodo print de el primer arco void Vertex: rintEdges(){if(edges==0) cout<<"\nvertice "<<getData()<<" no tiene arcos"<<endl; else { cout<<"\n vertice "<<getData()<<" tiene arcos a:"<<endl; edges->print(); } } //prints the edges of the vertex, calls the printGraph method for //the next vertex //imprime los arcos del vertice,llama al metodo printGraph del siguiente vertice void Vertex: rintGraph(){printEdges(); if(next!=0) next->printGraph(); } //adds an edge to connect the vertex to the vertex pointed to by Vert //agrega un arco para conectar el vertice a otro vertice apntado por Vert void Vertex::connectTo(Vertex *Vert){ //allocate memory for a new Edge, set its Vertes pointer to point //to Vert, and its Edge pointer to point to the rest of edges //asigna memoria para el nuevo arco,fija su puntero a vertice para señalar a Vert //y el puntero el puntero del arco apunta a el resto de los arcos Edge *newEdge = new Edge(Vert, edges); //make the new edge the first edge of the vertex //hace que el nuevo arco el primer arco del vertice edges = newEdge; } //returns the pointer to the next vertex in the graph //retorna el puntero al siguiente vertice en el garfo Vertex *Vertex::getNext(){ return next; } //returns the pointer to the first outcoming edge of the vertex //retorna el puntero de el primer arco que viene de fuera del vertice Edge *Vertex::getFirstEdge(){ return edges; } //*********************************************** //methods of class Edge //metodos de la clase arco //Constructor: sets the two fields to the two given values //constructor: fija los dos campos de los dos valores dados Edge::Edge(Vertex *Vert, Edge *nextEdge){ end=Vert; next=nextEdge; } //Destructor: calls the destructor for the next edge on the list //destructor: llama al destructor para siguiente arco de la lsita Edge::~Edge(){ delete next; } //returns the pointer to the end vertex of the edge //retorna el punerto de el vertice final del arco Vertex *Edge::getEnd(){ return end; } //prints out the data of the end of the edge, then calls the print method //of the next edge on the list (if there is one) //imprime el dato de el ultimo arco,entonces llama al metodo print de //el el arco siguiente en la lista(si hay uno) void Edge: rint(){cout<<end->getData()<<" "; if (next==0) cout<<endl; else{ next->print(); } } //returns the pointer to the next edge on the list //retorna el puntero de el siguiente arco de la lista Edge *Edge::getNext(){ return next; } //declaracion de la clase Graph class Graph{ public: Graph(); ~Graph(); Vertex *find(char); int AddVertex(char); int AddEdge(char, char); void print(); void ResetGraph(); int AllExplorer(); void Encolar(Vertex*); Vertex *getFrente(); void Profundidad(); void Amplitud(); private: Vertex *first; //a pointer to the first vertex of the graph //0 if the graph does not have vertexes //un puntero para el primer vertice del grafo //0 is el grafo no tiene vertices class Nodo{ public: Nodo(Vertex *newVertex){sig=0;vertex=newVertex;} Vertex *getVertex(){return vertex;} Vertex *vertex; Nodo *sig; };Nodo *frente,*cola; }; //Constructor: creates graph with no vertexes //constructor: crea grafo sin vertices Graph::Graph(){ first=0; frente=0; cola=0; } //Destructor: deletes the first vertex of the graph, which calls the vertex //destructor to delete its edges and the other vertexes with their edges //destructor: elimina el primer vertice de el grafo,cual llama al vertice destructor //para eliminar sua arco y los otros vertices con sus arcos Graph::~Graph(){ delete first; } //the method returns the pointer to the vertex with data theData //if such vertex occurs in the graph, otherwise returns 0 //el metodo retorna el puntero a el vertice con el dato theData //if tales vertices oacurren en el grafo, si no renorna 0 Vertex *Graph::find(char theData){ Vertex *vPtr = first; while (vPtr != 0){ //check if the data of the vertex is theData //comprueba si el dato del vertice es theData if (vPtr->getData()==theData) return vPtr; //go to the next vertex //va al siguiente vertice vPtr = vPtr->getNext(); } //there has been no match in the loop, so there is no such vertex //este no ha sido encontrado en el bucle,no hay tal vertice return 0; } //the method checks if there is a vertex with data theData in the graph //if yes, the vertex cannot be added, the method returns 'false' //otherwise the vertex is added, the method returns 'true' //el metodo comprueba si hay un vertice con el dato theData en el garfo //si hay, el vertice no es agregado, el metodo retorna false //si no el vertice es agregado,el metodo retorna 'true' int Graph::AddVertex(char theData){ //checking if the vertex is already in the graph //if it is, it cannot be added again //comprueba si el vertice ya esta en el grafo //si ya esta, no puede ser agregado otra vez if(find(theData) !=0) return 0; //allocate memory for new vertex with data theData, //make it point to the previous first vertex //asigna memoria para el vertice con el dato theData //hace el puntero al previo vertice anterior Vertex *newVertex = new Vertex(theData, first); //make the new vertex the first one in the list of vertexes //hace el nuevo vertice el primero en la lista de vertices first = newVertex; return 1; } //check if the vertexes with data Begin and End are, present in the graph. //if yes, create an edge from Begin to End, return 'true' //otherwise return 'false' //comprueba si los vertices //si si, cera un arco desde begin a end, y retorna 'true' //si no, retorna 'false' int Graph::AddEdge(char Begin, char End){ //find the pointer to the end vertex //find el puntero al vertice end Vertex *vEnd = find(End); //if the vertex is not in the graph, cannot add the edge //if el vertice no esta en el grafico, no se puede agregar el arco if(vEnd==0) return 0; //find the pointer to the start vertex //find el puntero a el inicio del vertice Vertex *vBegin = find(Begin); //if the vertex is not in the graph, cannot add the edge //if el vetice no esta en el grafo, no se puede agrgar el arco if(vBegin==0) return 0; //connect the start vertex to the end one //conecta el inicio del vertice con el extremo uno vBegin->connectTo(vEnd); return 1; } //print all vertexes and edges of the graph //muestra todos los vertices y arcos de el garfo void Graph: rint(){if(first==0) cout<<"\nGraph has no vertexes"<<endl; else first->printGraph(); } void Graph::ResetGraph() { Vertex *vTemp=first; while(vTemp!=0) { vTemp->ChangeStatus(0); vTemp=vTemp->getNext(); } } int Graph::AllExplorer() { int All=1; Vertex *vTemp=first; while(vTemp!=0) { if(vTemp->getStatus()==0) {All=0;} vTemp=vTemp->getNext(); } return All; } void Graph::Encolar(Vertex *newVertex) { Nodo *nTemp=new Nodo(newVertex); if(nTemp){ if(cola!=0){cola->sig=nTemp;} cola=nTemp; if(frente==0){frente=nTemp;} } } Vertex *Graph::getFrente() { Nodo *nTemp; Vertex *vFrente; nTemp=frente; if(nTemp!=0) { frente=frente->sig; vFrente=nTemp->getVertex(); delete nTemp; return vFrente; } return 0; } void Graph::Amplitud() { ResetGraph(); Vertex *vActual=first; Edge *eActual; cout<<"\nRecorrido por amplitud:\n"; while(vActual!=0 && vActual->getFirstEdge()!=0) { if(AllExplorer()==1) {return;} if(vActual->getStatus()==0) {cout<<vActual->getData()<<" "; vActual->ChangeStatus(1); } eActual=vActual->getFirstEdge(); while(eActual!=0) { if(eActual->getEnd()->getStatus()==0) { cout<<eActual->getEnd()->getData()<<" "; eActual->getEnd()->ChangeStatus(1); Encolar(eActual->getEnd()); } eActual=eActual->getNext(); } vActual=getFrente(); while(vActual==0 && frente!=0) { vActual=getFrente(); } } } void Graph::Profundidad() { ResetGraph(); Vertex *vTemp=first; Vertex *vCurrent; Edge *eCurrent; cout<<"\nRecorrido por profundidad:\n"; while(vTemp!=0) { vCurrent=vTemp; while(vCurrent->getFirstEdge()!=0) { if(vCurrent->getStatus()==0) {cout<<vCurrent->getData()<<" "; vCurrent->ChangeStatus(1); } eCurrent=vCurrent->getFirstEdge(); if(eCurrent->getEnd()->getStatus()==0) { cout<<eCurrent->getEnd()->getData()<<" "; eCurrent->getEnd()->ChangeStatus(1); } vCurrent->ChangeFirstEdge(eCurrent->getNext()); vCurrent=eCurrent->getEnd(); } vTemp=vTemp->getNext(); } } int main(){clrscr(); Graph myGraph; myGraph.AddVertex('E'); myGraph.AddVertex('D'); myGraph.AddVertex('C'); myGraph.AddVertex('B'); myGraph.AddVertex('A'); myGraph.AddEdge('A', 'B'); myGraph.AddEdge('A', 'C'); myGraph.AddEdge('A', 'D'); myGraph.AddEdge('B', 'D'); myGraph.AddEdge('D', 'E'); myGraph.AddEdge('E', 'B'); myGraph.AddEdge('B', 'C'); myGraph.AddEdge('A', 'A'); myGraph.AddEdge('E', 'A'); myGraph.print(); getch(); return 0; }
__________________
El ConoCIMIenTo no lleGA poR si solo,<br />soLO kE el MEdio pARA oBteNERlo es .......... |
|
|
|
| El Siguiente Usuario Agradeció a jaker_lolo Por Este Mensaje: | bea3 (05-oct-2010) |
|
|
#2 | |||
|
Guest
Amigos
Mensajes: n/a
|
Hola, bueno... apenas si me empiezo a sentir cómodo con C, por lo cual no tengo much idea de c++, pero si te sirve:
(cotiene código en java + applet de ejemplo)
(ejemplos en c, c++ y python)
(varios shortest path) Espero te sea (al menos) minimamente util. |
|||
|
|
|
#3 | |
|
Guest
Amigos
Mensajes: n/a
|
Fijate ahí, que tienen una librería de grafos (Graph), y dentro de esa librería hay una implementación del algoritmo de Dijkstra. |
|
|
![]() |
| Herramientas | |
| Desplegado | |
|
|
