给定一个包含非负整数的 m x n 网格,请找出一条从左上角到右下角的路径,使得路径上的数字总和为最小。
说明:每次只能向下或者向右移动一步。
示例:
输入: [ [1,3,1], [1,5,1], [4,2,1] ] 输出: 7 解释: 因为路径 1→3→1→1→1 的总和最小。
很惭愧,我一开始审题不认真就没发现只能向下或者向右的规定,不过感觉不规定这个更合理,以下是不规定的时候的情况。(如果有只有限定向下或者向右,就将dir数组修改一下(代码中是右下角往左上角行动))
补充:这道题题目只能向下或者向右,没计算绕路的情况,例如:
1 | 1 | 1 | 1 | 1 |
10 | 10 | 10 | 10 | 1 |
10 | 10 | 1 | 1 | 1 |
10 | 10 | 1 | 10 | 10 |
10 | 10 | 1 | 1 | 1 |
上面表格的地图很明显按全是1的方向走比较合理,只要13就可以到目的地,而不应该无脑上左前进;
所以我的具体实现方法如下(新增了打印路径来检查路径是否正确):
//64
public int minPathSum(int[][] grid) {
int x = grid.length - 1;
int y = grid[0].length - 1;
int[] p = new int[3];
p[0] = x;
p[1] = y;
p[2] = grid[x][y];
int[][] status = new int[x + 1][y + 1];
for (int i = 0; i < status.length; i++) {
for (int j = 0; j < status[i].length; j++) {
status[i][j] = Integer.MAX_VALUE;
}
}
int[][] dir = new int[4][2];
dir[0][0] = 0;
dir[0][1] = 1;
dir[1][0] = 0;
dir[1][1] = -1;
dir[2][0] = 1;
dir[2][1] = 0;
dir[3][0] = -1;
dir[3][1] = 0;
Queue<int[]> queue = new LinkedList<>();
queue.add(p);
int res = Integer.MAX_VALUE;
//打印路径
Map<String, List<int[]>> road = new HashMap<>();
List<int[]> r = new LinkedList<>();
r.add(p);
String str = "x=" + p[0] + ",y=" + p[1];
road.put(str, r);
while (!queue.isEmpty()) {
int[] t = queue.poll();
int tx = t[0];
int ty = t[1];
int tv = t[2];
if (tx == 0 && ty == 0) {
res = res > tv ? tv : res;
}
for (int[] di : dir) {
if (tx + di[0] < 0 || tx + di[0] > x) {
continue;
}
if (ty + di[1] < 0 || ty + di[1] > y) {
continue;
}
if (tv + grid[tx + di[0]][ty + di[1]] >= status[tx + di[0]][ty + di[1]]) {
continue;
}
status[tx + di[0]][ty + di[1]] = tv + grid[tx + di[0]][ty + di[1]];
int[] np = new int[3];
np[0] = tx + di[0];
np[1] = ty + di[1];
np[2] = tv + grid[tx + di[0]][ty + di[1]];
queue.add(np);
//添加路径
String nstr = "x=" + (tx + di[0]) + ",y=" + (ty + di[1]);
String ostr = "x=" + tx + ",y=" + ty;
List<int[]> oldr = road.get(ostr);
List<int[]> newr = new LinkedList<>();
for(int[] i:oldr){
newr.add(i);
}
newr.add(np);
road.put(nstr,newr);
}
}
str = "x=" + 0 + ",y=" + 1;
String str2 = "x=" + 1 + ",y=" + 0;
List<int[]> resr1 = road.get(str);
List<int[]> resr2 = road.get(str2);
return res;
}