【发布时间】:2019-03-31 02:18:29
【问题描述】:
我想打印出这个二维数组中所有可能的路径。我还希望能够编辑路径的起点和终点。我已经想出了如何编辑起点而不是目的地。如何编辑我的代码来解决这个问题?例如,可能所有路径都在 E5 而不是 G5 结束。
public class Test {
int rowCount;
int colCount;
int[][] arrA;
char [] columnName = {'A', 'B', 'C', 'D', 'E', 'F', 'G'};
//Constructor
public Test(int arrA[][]) {
this.arrA = arrA;
rowCount = arrA.length;
colCount = arrA[0].length;
}
//Function which prints all possible paths
public void printAll(int currentRow, int currentColumn, String path) {
if (currentRow == rowCount - 1) {
for (int i = currentColumn; i < colCount; i++) {
path += "->" + columnName[i]+(currentRow+1);
}
System.out.println(path);
return;
}
if (currentColumn == colCount - 1) {
for (int i = currentRow; i <= rowCount - 1; i++) {
path += "->" + columnName[currentColumn]+(i+1);
}
System.out.println(path);
return;
}
if(path.isEmpty())
{
path = path + columnName[currentColumn]+(currentRow+1);
}
else{
path = path + "->" + columnName[currentColumn]+(currentRow+1);
}
printAll(currentRow + 1, currentColumn, path);
printAll(currentRow, currentColumn + 1, path);
}
//Driver Function
public static void main(String args[]) {
int[][] grid = { { 0, 1, 2, 3, 4, 5, 6 },
{ 1, 2, 3, 4, 5, 6, 7 },
{ 2, 3, 4, 5, 6, 7, 8 },
{ 3, 4, 5, 6, 7, 8, 9 },
{ 4, 5, 6, 7, 8, 9, 10}
};
Test p = new Test(grid);
p.printAll(0, 0, "");
}
}
【问题讨论】:
-
您的问题与您的标题不符
-
您是在问如何应用停止条件?