# ！怎么将如下的递归代码变成迭代

www.MyException.Cn  网友分享于：2013-06-03  浏览：8次

Java code
```
public int longestPath(int start,int[] topo){
int longest = 0;
for(int v:topo){
if(isArc(start,v)){
int temp = longestPath(v,topo)+1;
if(longest < temp){
longest = temp;
}
}
}
return longest;
}
public long getNumOfPaths(int v,int[] topo){
long numOfPaths = 0;
if(v==0){
numOfPaths =  1;
}else{
for(int i:topo){
if(isArc(i,v)){
numOfPaths += getNumOfPaths(i,topo);
}
}
}
return numOfPaths;
}

```

------解决方案--------------------
public int longestPath3(int start,int[] topo,Graph dagRev,int[] dist,int[] turn){
int temp;
for(int v : topo){
temp = 0;
if(turn[v]<=turn[start]||dagRev.neighbors(v).isEmpty()){
dist[v]=0;
}else{
for(int u:dagRev.neighbors(v)){
if(dist[u]==0&&u!=start){
temp = 0;
}else{
temp = dist[u] + 1;
}
if(dist[v]<temp){
dist[v]=temp;
}
}
}
}
int longest = getMax(dist);
return longest;
}
public int getMax(int[] dist){
int max = dist[0];
for(int i : dist){
if(max<i){
max = i;
}
}
return max;
}
public long getNumsOfPath3(int start,int[] topo, Graph dagRev, long[] pathsNums, int[] turn){
for(long i:pathsNums){
i = 0;
}
for(int v:topo){
if(turn[v]<turn[start]){
pathsNums[v]=0;
}else if(v==start){
pathsNums[v] = 1;
}else{
for(int u:dagRev.neighbors(v)){
pathsNums[v]+=pathsNums[u];
}
}
}
return pathsNums[order()-1];
}