问题描述
目前,我有一个能找到最长路径的有效算法。但是,当我尝试打印出路径时,它会打印出找到最长路径所需的所有路径。我该如何解决?
我厌倦了走回原路,这导致了错误的答案,但输出却少了一些(在这种情况下,输出少了大约400条)。还是应该制作另一个ArrayList来存储正确的路径?既然代码运行起来,我应该怎么做才能想到所有可能。还是我应该以某种方式修改代码?
import java.util.*;
import java.awt.Point;
class Main
{
// M x N matrix
private static final int M = 10;
private static final int N = 10;
static ArrayList<Point> Path = new ArrayList<Point>();
// check if it is possible to go to position (x,y) from
// current position. The function returns false if the cell
// has value 0 or it is already visited.
private static boolean isSafe(int mat[][],int visited[][],int x,int y) {
if (mat[x][y] == 0 || visited[x][y] != 0)
return false;
return true;
}
// if not a valid position,return false
private static boolean isValid(int x,int y) {
if (x < M && y < N && x >= 0 && y >= 0)
return true;
return false;
}
// Find Longest Possible Route in a Matrix mat from source
// cell (0,0) to destination cell (x,y)
// 'max_dist' stores length of longest path from source to
// destination found so far and 'dist' maintains length of path from
// source cell to the current cell (i,j)
public static int findLongestPath(int mat[][],int i,int j,int y,int max_dist,int dist) {
// if destination not possible from current cell
if (mat[i][j] == 0) {
return 0;
}
// if destination is found,update max_dist
if (i == x && j == y) {
return Integer.max(dist,max_dist);
}
// set (i,j) cell as visited
visited[i][j] = 1;
// go to bottom cell
if (isValid(i + 1,j) && isSafe(mat,visited,i + 1,j)) {
max_dist = findLongestPath(mat,j,x,y,max_dist,dist + 1);
}
// go to right cell
if (isValid(i,j + 1) && isSafe(mat,i,j + 1)) {
max_dist = findLongestPath(mat,j + 1,dist + 1);
}
// go to top cell
if (isValid(i - 1,i - 1,dist + 1);
}
// go to left cell
if (isValid(i,j - 1) && isSafe(mat,j - 1)) {
max_dist = findLongestPath(mat,j - 1,dist + 1);
}
// Backtrack - Remove (i,j) from visited matrix
visited[i][j] = 0;
Point temp = new Point(i,j);
Path.add(temp);
return max_dist;
}
public static void main(String[] args)
{
// input matrix
int mat[][] =
{
{ 1,1,1 },{ 1,{ 0,0 },0 }
};
// construct a matrix to keep track of visited cells
int[][] visited= new int[N][N];
// (0,0) are the source cell coordinates and (5,7) are the
// destination cell coordinates
int max_dist = findLongestPath(mat,5,7,0);
System.out.println("Maximum length path is " + max_dist);
Collections.reverse(Path);
int i = 1;
for (Point point : Path) {
System.out.println(i + " " + point.toString());
i++;
}
}
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)