Google - 3

Question

Bomb Game,给一个m*n的二维数组,其中有: -1 墙, 1 怪兽, 0 空白。 你有一个炸弹,可以扔在除墙之外的任意位置,最多可以炸死几个怪兽。
炸弹爆炸可以清除这个炸弹所在的一行和一列的怪兽,但是不能穿过墙.

Algorithm

Create a matrix with same number of row and column like input matrix. This matrix stores values that for each point, how many monsters at left and top including itself. Create a array whose size is number of columns of input matrix. This array stores how many monsters at top of current point. For each row, we create a max variable to store how many monsters at left of the point.

Code

public int getMax(int[][] matrix) {
    int rows = matrix.length;
    int cols = matrix[0].length;
    int[][] num = new int[rows][cols]
    int[] topMax = new int[cols];
    for (int i = 0; i < rows; i++) {
        int leftMax = 0;
        for (int j = 0; j < cols; j++) {
            if (matrix[i][j] == -1) {
                leftMax = 0;
                topMax[j] = 0;
                num[i][j] = 0;
            } else {
                if (j == 0) {
                    leftMax = matrix[i][j];
                } else {
                    leftMax += matrix[i][j];
                }
                if (i == 0) {
                    topMax[j] = matrix[i][j];
                } else {
                    topMax[j] += matrix[i][j];
                }
                num[i][j] = topMax[j] + leftMax;
            }
        }
    }
    int[] bottomMax = new int[cols];
    int totalMax = 0;
    for (int i = rows - 1; i >= 0; i--) {
        int rightMax = 0;
        for (int j = cols - 1; j >= 0; j--) {
            if (matrix[i][j] == -1) {
                rightMax = 0;
                bottomMax[j] = 0;
            } else {
                if (j == cols - 1) {
                    rightMax = matrix[i][j];
                } else {
                    rightMax += matrix[i][j];
                }
                if (i == rows - 1) {
                    bottomMax[j] = matrix[i][j];
                } else {
                    bottomMax[j] += matrix[i][j];
                }
                int tempMax = num[i][j] + bottomMax[j] + rightMax;
                if (matrix[i][j] == 1) {
                    tempMax -= 3;
                }
                totalMax = Math.max(tempMax, totalMax);
           }
       }
    }
    return totalMax;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,797评论 0 23
  • 前几天武汉面基,我当日挖了一个坑,后来没有修改那一份内容,而是开了新的文来填坑。 今天来谈一谈“演绎”。这是谷应老...
    时光蜜糖阅读 708评论 4 50
  • 又是一个中秋节,遥想儿时,每每到节日便异常的开心。这一天,乡下必须过得有些仪式感,现在这种感觉慢慢的淡了。原因且不...
    夏荷酱阅读 219评论 0 0
  • 突然忙碌的日子变得慢一些了,莫名有点舍不得,尽管紧张会让我月经不调~ 我喜欢格子化的生活;我喜欢想得稍微远一点,其...
    小小的大大阅读 248评论 0 0
  • 和科技做朋友。她说:这是一个科技可以创造惊喜的时代,生活中有各种各样科技带来的便利和美好,拥抱科技敢于创新,请相信...
    fromhere阅读 238评论 0 0