我一直致力于设计一个代码,用于在2D数组中打印出“运动总和”。 我得到了一个带有正整数的矩阵用于条目,具有起始位置NW并且它应该在SE结束,并且对于每个这样的路径,我被要求该路径的总权重(相关条目的“总和”)。 为了使事情更清楚,我要求记录下面的任何步骤。 问题是,我没有错误,但方法的第一步是错误的 - 它总是首先上升。我不知道哪一步让它发生了。你能发现任何错误吗?
public class question02
{
public static void printPathWeights(int [][] m)
{
pathing (m, 0, 0, 0);
}
private static void pathing (int [] [] m , int currH , int currV , int value)
{
if ( validPath( m , currH - 1 , currV ) == true ) //up
{
value += m[currH][currV];
int tmp = m[currH][currV];
m[currH][currV] = -1;
System.out.println ("going up");
pathing ( m , currH - 1, currV , value );
m[currH][currV] = tmp;
}
if ( validPath( m , currH + 1 , currV ) == true ) //down
{
value += m[currH][currV];
int tmp = m[currH][currV];
m[currH][currV] = -1;
System.out.println ("going down");
pathing ( m , currH + 1, currV , value );
m[currH][currV] = tmp;
}
if ( validPath( m , currH , currV - 1 ) == true ) //left
{
value += m[currH][currV];
int tmp = m[currH][currV];
m[currH][currV] = -1;
System.out.println ("going left");
pathing ( m , currH , currV - 1 , value );
m[currH][currV] = tmp;
}
if ( validPath( m , currH , currV + 1 ) == true ) //right
{
value += m[currH][currV];
int tmp = m[currH][currV];
m[currH][currV] = -1;
System.out.println ("going right");
pathing ( m , currH , currV + 1 , value );
m[currH][currV] = tmp;
}
if ( currH == m.length -1 && currV == m[0].length -1 ) //end
{
System.out.println (value);
}
}
private static boolean validPath (int [] [] m , int possH , int possV )
{
if ( ( possH < 0 ) || ( possH >= m.length - 1 ) || ( possV < 0 ) || ( possV >= m[0].length - 1 ) )
{
return false;
}
if (m[possH][possV] == -1)
{
return false;
}
else return true;
}
}