public void addEdge(int src, int dest, int weight) { // Add an edge from src to dest. A new node is added to the adjacency // list of src. The node is added at the beginning AdjListNode newNode = new AdjListNode(dest, weight); newNode.next = this.array[src].head; this.array[src].head = newNode; // Since graph is undirected, add an edge from dest to src also newNode = new AdjListNode(src, weight); newNode.next = this.array[dest].head; this.array[dest].head = newNode; }
//public static void printArr(Cell[] dist, int n) //{ // Console.WriteLine("\n\n Vertex \t\t Distance from Source \t\t parent \n"); // for (int i = 0; i < n; ++i) // Console.WriteLine("\n" + i + " \t\t " + dist[i].distance + " \t\t" + dist[i].Parent); //} // The main function that calulates distances of shortest paths from src to all // vertices. It is a O(ELogV) function public static Cell[] Dijkstra(Graph graph, int src) { int vv = graph.v; // Get the number of vertices in graph Cell[] dist = new Cell[vv]; // dist values used to pick minimum weight edge in cut for (int i = 0; i < vv; i++) { dist[i] = new Cell(); dist[i].i = src; dist[i].j = i; dist[i].Parent = 0; dist[i].distance = int.MaxValue; } // minHeap represents set E MinHeap minHeap = new MinHeap(vv); // Initialize min heap with all vertices. dist value of all vertices for (int v = 0; v < vv; ++v) { dist[v].distance = int.MaxValue; minHeap.array[v] = new MinHeapNode(v, dist[v].distance); minHeap.pos[v] = v; } // Make dist value of src vertex as 0 so that it is extracted first minHeap.array[src] = new MinHeapNode(src, dist[src].distance); minHeap.pos[src] = src; dist[src].distance = 0; minHeap.decreaseKey(src, dist[src].distance); // Initially size of min heap is equal to V minHeap.size = vv; // In the followin loop, min heap contains all nodes // whose shortest distance is not yet finalized. while (!minHeap.isEmpty()) { // Extract the vertex with minimum distance value MinHeapNode minHeapNode = minHeap.extractMin(); int u = minHeapNode.v; // Store the extracted vertex number // Traverse through all adjacent vertices of u (the extracted // vertex) and update their distance values AdjListNode pCrawl = graph.array[u].head; while (pCrawl != null) { int v = pCrawl.dest; // If shortest distance to v is not finalized yet, and distance to v // through u is less than its previously calculated distance if (minHeap.isInMinHeap(v) && dist[u].distance != int.MaxValue && pCrawl.weight + dist[u].distance < dist[v].distance) { dist[v].distance = dist[u].distance + pCrawl.weight; dist[v].Parent = u; // update distance value in min heap also minHeap.decreaseKey(v, dist[v].distance); } pCrawl = pCrawl.next; } } // print the calculated shortest distances //printArr(dist, vv); return(dist); }
public int SetHead() { head = null; return(1); }
// A utility function to create a new adjacency list node public AdjListNode(int dest, int weight) { this.dest = dest; this.weight = weight; this.next = null; }