【Lintcode】1896. Pick Carrots

题目地址:

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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值