Wednesday, October 24, 2007

Solution to MGPT 2007 question no 2.....

This is the solution to MGPT 2007 question no 2.... (85 lines)
I could clear only this question in the MGPT....
The rest I did after the MGPT...


import ncst.pgdst.*;
class Vertex{
char data;
int edgeCount;
Vertex[]edge;
boolean visited;
Vertex(char n){
data=n;
edge=new Vertex[50];
edgeCount=-1;
visited=false;
}
}
class Graph{
Vertex[]vertex;
int vertexCount;
int hops=0;
int min=999999;
Graph(){
vertex=new Vertex[50];
vertexCount=-1;
}
void addVertex(char n){
vertex[++vertexCount]=new Vertex(n);
}
void addEdge(char v1,char v2){
int posv1=findIndex(v1);
int posv2=findIndex(v2);
if(posv1==-1 posv2==-1) return;
int p=++(vertex[posv1].edgeCount);
vertex[posv1].edge[p]=vertex[posv2];
}
int findIndex(char v){
for(int i=0;i<=vertexCount;i++)
if(vertex[i].data==v) return i;
return -1;
}
void dfs(char v1,char v2){
int p1=findIndex(v1);
Stack stack=new Stack();
stack.push(vertex[p1].data);
while(!stack.isEmpty()){
boolean found=false;
int n=findIndex(stack.peek());
for(int i=0;i<=vertex[n].edgeCount;i++){
if(vertex[n].edge[i].visited==true) continue;
stack.push(vertex[n].edge[i].data);
vertex[n].edge[i].visited=true;
++hops;
found=true;
if(vertex[n].edge[i].data==v2){
if(hops//{
//System.out.println("hops = "+hops);
min=hops;
//}
}
break;
}
if(!found){
unvisitChildren(stack.peek());
stack.pop();
--hops;
}
}
if(min==999999)
System.out.println("UNREACHABLE");
else
System.out.println(min);
}
public static void main(String[]args)throws IOException{
SimpleInput in=new SimpleInput();
Graph g=new Graph();
in.skipWhite();
int n=in.readInt();
for(int i=0;iin.skipWhite();
char v1=in.readChar();
in.skipWhite();
char v2=in.readChar();
if(g.findIndex(v1)==-1) g.addVertex(v1);
if(g.findIndex(v2)==-1) g.addVertex(v2);
g.addEdge(v1,v2);
}
in.skipWhite();
char v1=in.readChar();
in.skipWhite();
char v2=in.readChar();
g.dfs(v1,v2);
}
void unvisitChildren(char n){
int p=findIndex(n);
for(int i=0;i<=vertex[p].edgeCount;i++)
vertex[p].edge[i].visited=false;
}
}
class Stack{
char[]a=new char[100];
int top=-1;
void push(char n){ a[++top]=n; }
char peek() { return a[top]; }
void pop() { --top; }
boolean isEmpty(){ return top==-1; }
}


If you are unable to see the program in a proper format, please click this link
http://chandra-shekhar.spaces.live.com/default.aspx

No comments: