# 3. Graph algorithm. Write an algorithm that finds the length of the longest path starting from vertex 0 in a DAG

Name it path.java. Your program should be effcient, i.e. it must complete with the correct answer within 10 seconds for any feasible type of input!

3. Graph algorithm. Write an algorithm that finds the length of the longest path starting from vertex 0 in a DAG Input format. The input consists of a sequence of one or more DAGs. Each DAG D is represented by an adjacency list. The first line is an integer n that indicates the order of D. This is followed by n white space separated lists of adjacencies for vertices labeled 0 to n 1. The input is terminated by a line consisting of a single zero. This line should not be processed. Each input DAG may contain up to 5000 vertices and 10000 arcs. An example input that contains two DAGs is shown next

import java.util.*;

import java.io.*;

public class LongestPath {
int             n;        // number of nodes
int     target;    // destination node
int           minLength; // the minimal length of each path
Node[]    v;        //used to store Nodes
Edge[]    e;        //used to store Edges

int[]     path;     //used to store temporary path
int       length=0;       // length of the path
int   distance=0;    // distance of the path
int[]     bestPath;       //used to store temporary path
int       bestLength=0;         // length of the longest path
int   bestDistance=-1000000;     // distance of the longest path

int[] visited; //used to mark a node as visited if set as 1

public LongestPath () {}

public LongestPath (String filename) throws IOException {
//this function read edge distances from a file
StringTokenizer st = new StringTokenizer (line);
//1st token is the # of nodes
n = Integer.parseInt (st.nextToken());

//2nd token is the # of edges
int m = Integer.parseInt (st.nextToken());

//create storage for Nodes and Edges
v = new Node[n];
e = new Edge[m];
System.out.println(n+” nodes and ” + m + ” edges.”);

//create Node objects for graph
//numbering them as 0, 1, 2, …, n-1
for (int i = 0; i < n; i++)
v[i] = new Node(i);

int i = 0;
//check input file
if (i >= e.length){
System.out.println (“# of lines is greater than # of edges in G, exit…”);
System.exit(1);
}

Edge edge = new Edge(i);
st = new StringTokenizer (line);

//first token is the start point
String start = st.nextToken();
int sVal = Integer.parseInt (start);
edge.start = sVal;

//2nd token is the end point
String end = st.nextToken();
int eVal = Integer.parseInt (end);
edge.end = eVal;

//3rd token is weight, the same as capacity
String capacity = st.nextToken();
edge.capacity = Integer.parseInt (capacity);

System.out.println(” edge: “+edge.start+” “+edge.end+” “+edge.capacity);

edge.flow = 0;
e[i] = edge;
//map[sVal][eVal] = i;

//now save edge information in nodes start and end

i++;
if (i == m) break;
}

visited = new int[v.length];
path = new int[v.length];
bestPath = new int[v.length];
}

// this function looks for a longest path starting from being to end,
// using the backtrack depth-first search.
public boolean findLongestPath(int begin, int end, int minLen){
// compute a longest path from begin to end
target = end;
bestDistance = -100000000;
minLength = minLen;
dfsLongestPath(begin);
if (bestDistance == -100000000) return false; else return true;
}

private void dfsLongestPath(int current) {
visited[current] = 1;
path[length++] = current;

if (current == target && length >= minLength) { // a path from source to target is found.
if (distance > bestDistance) { // if a longer path is found
for (int i = 0; i < length; i++) bestPath[i] = path[i];
bestLength = length;
bestDistance = distance;
}
} else {
//get current’s edges
Vector<Integer> fors = v[current].fors;

//select an unvisited forward edge
for (int i = 0; i < fors.size(); i++) {
Integer edge_obj = (Integer)fors.elementAt(i);
int edge = edge_obj.intValue();

if (visited[e[edge].end] == 0) {//not yet visited
distance += e[edge].capacity;
dfsLongestPath(e[edge].end);
distance -= e[edge].capacity;
}
}
}

// finish with current and unmark current.
visited[current] = 0;
length–;
}

public String toString() {
String output = “v” + bestPath[0];
for (int i = 1; i < bestLength; i++) output = output + ” -> v” + bestPath[i];
return output;
}

public static void main (String arg[]){
LongestPath lp = new LongestPath();
try {
lp = new LongestPath(“graph1.txt”);
}
catch (IOException e){
System.exit(1);
}

// find a longest path from vertex 0 to vertex n-1.
if (lp.findLongestPath(0, lp.n-1, 1))
System.out.println (“Longest Path is ” + lp + ” and the distance is ” + lp.bestDistance);
else System.out.println(“No path from vertex0 to v” + (lp.n-1));

// find a longest path from vertex 3 to vertex 5.
if (lp.findLongestPath(3, 5, 1))
System.out.println (“Longest Path is ” + lp + ” and the distance is ” + lp.bestDistance);
else System.out.println(“No path from vertex3 to vertex5”);

// find a longest path from vertex 5 to vertex 3.
if (lp.findLongestPath(lp.n-1, 3, 1))
System.out.println (“Longest Path is ” + lp + ” and the distance is ” + lp.bestDistance);
else System.out.println(“No path from vertex5 to vertex3”);

}
}

Pages (550 words)
Approximate price: -

Help Me Write My Essay - Reasons:

Best Online Essay Writing Service

We strive to give our customers the best online essay writing experience. We Make sure essays are submitted on time and all the instructions are followed.

Our Writers are Experienced and Professional

Our essay writing service is founded on professional writers who are on stand by to help you any time.

Free Revision Fo all Essays

Sometimes you may require our writers to add on a point to make your essay as customised as possible, we will give you unlimited times to do this. And we will do it for free.

Timely Essay(s)

We understand the frustrations that comes with late essays and our writers are extra careful to not violate this term. Our support team is always engauging our writers to help you have your essay ahead of time.

Customised Essays &100% Confidential

Our Online writing Service has zero torelance for plagiarised papers. We have plagiarism checking tool that generate plagiarism reports just to make sure you are satisfied.

Try it now!

## Calculate the price of your order

Total price:
\$0.00

How it works?

Fill in the order form and provide all details of your assignment.

Proceed with the payment

Choose the payment system that suits you most.

HOW OUR ONLINE ESSAY WRITING SERVICE WORKS

Let us write that nagging essay.

By clicking on the "PLACE ORDER" button, tell us your requires. Be precise for an accurate customised essay. You may also upload any reading materials where applicable.

Pick A & Writer

Our ordering form will provide you with a list of writers and their feedbacks. At step 2, its time select a writer. Our online agents are on stand by to help you just in case.

Editing (OUR PART)

At this stage, our editor will go through your essay and make sure your writer did meet all the instructions.