题解 | JAVA #最大正方形# [P0-T2]

最大正方形

http://www.nowcoder.com/practice/0058c4092cec44c2975e38223f10470e

mem[i][j]: 右下角坐标为(i,j)分正方形最大边长

if matrix[i][j] = 1: 
  mem[i][j] = 1+ MIN{
     mem[i-1][j], 
     mem[i-1][j-1], 
     mem[i][j-1]
  }
import java.util.*;

public class Solution {
    public int solve (char[][] matrix) {
      if (matrix.length == 0 || matrix[0].length == 0) return 0;
      
      // 把char换成int. 题目给char是真的烦
      int[][] mem = new int[matrix.length][matrix[0].length];
      for (int i = 0; i < matrix.length; i++) {
        for (int j = 0; j < matrix[0].length; j++) {
          mem[i][j] = (matrix[i][j] == '1') ? 1 : 0;
        }
      }
      
      int maxW = 0;
      // mem[0][j] and mem[i][0]都等于matrix[i][j], 不用再算
      for (int i = 1; i < matrix.length; i++) {
        for (int j = 1; j < matrix[0].length; j++) {
          if (mem[i][j] == 0) {
            continue;
          }
          mem[i][j] = 1 + Math.min(mem[i-1][j], 
                                   Math.min(mem[i][j-1], mem[i-1][j-1]));
          maxW = Math.max(maxW, mem[i][j]);
        }
      }
      
      return maxW * maxW;
    }
}
全部评论

相关推荐

05-21 15:47
门头沟学院 Java
浪漫主义的虹夏:项目有亮点吗,第一个不是纯玩具项目吗,项目亮点里类似ThreadLocal,Redis储存说难听点是花几十分钟绝大部分人都能学会,第二个轮子项目也没体现出设计和技术,想实习先沉淀,好高骛远的自嗨只会害了自己
点赞 评论 收藏
分享
05-29 22:11
门头沟学院 Java
Elastic90:抛开学历造假不谈,这公司的招聘需求也挺怪的,Java开发还要求你有图文识别、移动端开发和c++的经验,有点逆天了。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务