【发布时间】:2015-09-18 15:54:54
【问题描述】:
任务:
给定一个包含全非负数的二维数组m,我们将定义一个“路径”作为相邻单元格的集合(对角线步骤不算邻居)从row == 0 && col == 0 开始并以row == m.length - 1 && col == m[0].length - 1 结束。
“路径”的成本是“路径”的每个单元格中的值的总和。
示例:
数组中的两个可能路径:
路径1的成本(虚线):8 + 4 + 2 + 8 + 9 + 9 + 7 + 5 = 52;
路径2的成本(全线):8 + 6 + 3 + 8 + 9 + 4 + 1 + 2 + 1 + 7 + 6 + 5 = 60
待办事项:
编写一个static 递归方法,该方法接受一个二维数组m,其中填充了整个非负值,并打印所有可能路径成本的总和(您可以假设m 是不是null 也不是空的)。
方法签名是(允许重载):
public static void printPathWeights(int [][] m)
我的代码:
public class Main {
public static void main(String[] args) {
int arr[][] = { { 1, 1, 1 },
{ 1, 1, 1 },
{ 1, 1, 1 }
};
printPathWeights(arr);
}
public static void printPathWeights(int[][] m) {
System.out.println(printPathWeights(m, 0, 0, new int[m.length][m[0].length], 0));
}
/*
* @param map marks the visited cells
*/
private static int printPathWeights(int[][] m, int row, int col, int[][] map, int carrier) {
if (row < 0 || col < 0 || row >= m.length || col >= m[0].length || map[row][col] == 1)
return 0;
if (row == m.length - 1 && col == m[0].length - 1)
return m[row][col] + carrier;
map[row][col] = 1;
return printPathWeights(m, row + 1, col, map, carrier + m[row][col]) +
printPathWeights(m, row - 1, col, map, carrier + m[row][col]) +
printPathWeights(m, row, col + 1, map, carrier + m[row][col]) +
printPathWeights(m, row, col - 1, map, carrier + m[row][col]);
}
}
上面代码的打印值为:14
低于预期!
当运行时:
int arr[][] = { { 1, 1 },
{ 1, 1 }
};
结果如预期的那样是 6。
我的代码有什么问题?
PS:请不要向我提供解决任务的代码,但请解释我的代码有什么问题。
【问题讨论】:
-
地图[行][列] = 1;再考虑一下这个逻辑
-
我假设
map应该是 visited 地图?如果是这样,请考虑以下探索顺序:路径 1:down,路径 2:left,down,right .探索在此处停止,因为您已经访问了路径 1 中的此节点。 -
@HunterLarco 将当前的
rowcol标记为 1 有什么问题? -
@DimaMaligin 假设两条不同的路径访问同一个单元格。用 1 标记单元格意味着它已被访问。所以第一条路径到达单元格,它被标记为已访问。第二条路径到达单元格,但它已被标记为已访问 -> 路径的结尾,尽管它会继续该单元格。