题目地址:
https://www.lintcode.com/problem/pick-carrots/description
给定一个 m × n m\times n m×n的矩阵 A A A,保证每个位置的数都是正的,其代表该位置的胡萝卜数量。从矩阵中心点出发(中心点的意思是正中央的行与列;如果行数列数是偶数,则取偏左或者偏上的),每次都朝四个方向中胡萝卜最多的方向走一步,如果四个方向都没有胡萝卜,则停止。问最后总共采了多少个胡萝卜。
代码如下:
public class Solution {
/**
* @param carrot: an integer matrix
* @return: Return the number of steps that can be moved.
*/
public int PickCarrots(int[][] carrot) {
// write your code here
int m = carrot.length, n = carrot[0].length;
int x = (m - 1) >> 1, y = (n - 1) >> 1;
int res = carrot[x][y], dir = 0;
int[] d = {1, 0, -1, 0, 1};
while ((dir = getDir(x, y, carrot, d)) != -1) {
carrot[x][y] = 0;
x += d[dir];
y += d[dir + 1];
res += carrot[x][y];
}
return res;
}
// 判断下一步走哪个方向
private int getDir(int x, int y, int[][] carrot, int[] d) {
// max记录最多的胡萝卜数,maxDir记录最多胡萝卜的方向
int max = 0, maxDir = -1;
for (int i = 0; i < 4; i++) {
int nextX = x + d[i], nextY = y + d[i + 1];
if (inBound(nextX, nextY, carrot)) {
if (carrot[nextX][nextY] > max) {
max = carrot[nextX][nextY];
maxDir = i;
}
}
}
// 如果四周都是0,则返回-1,不用走了;否则返回方向
return max == 0 ? -1 : maxDir;
}
private boolean inBound(int x, int y, int[][] carrot) {
return 0 <= x && x < carrot.length && 0 <= y && y < carrot[0].length;
}
}
时间复杂度 O ( m n ) O(mn) O(mn),空间 O ( 1 ) O(1) O(1)。