码迷,mamicode.com
首页 > 其他好文 > 详细

Maximal Square (leeCode)

时间:2015-06-03 17:45:21      阅读:101      评论:0      收藏:0      [点我收藏+]

标签:动态规划

Given a 2D binary matrix filled with 0‘s and 1‘s, find the largest square containing all 1‘s and return its area.

For example, given the following matrix:

1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
Return 4.
  /*
     * 动态规划的算法 
     *if(m[i][j] = 1) d[i][j] = min(d[i-1][j-1], d[i][j-1], d[i-1][j]) + 1
     *m[i][j] = 0; d[i][j] = 0;     
     *初始化 d[0][j] = m[0][j]; d[i][0] = m[i][0];
     *优化思路用一行d[j] 进行
     *int preNode = d[0];
     *d[0] = m[i][0];
     * for(int j = 1; j < n; j++)
     * { 
     *   if(m[i][j] = 1) int temp = min(preNode, d[j-1], d[j]) + 1;
     *   preNode = d[j];
     *   d[j] = temp;
     * }
     *错误1:没有考虑<1,0,1,1>向量 ;把矩阵想成等宽高的
     */
int min(int a, int b)
     {
         return a < b ? a : b;
     }
     int min(int a, int b, int c)
     {
         return min(min(a,b),min(b,c));
     }
int maximalSquare(vector<vector<char>>& m) {
        if(m.size() == 0) return 0;
        int m_size = m.size();
       // if(m_size == 1) return (m[0][0] == '0') ? 0 : 1;
        int* d = new int[m[0].size()];
        int max = 0;
        //init
        for(int i = 0; i < m[0].size(); i++)
        {
            d[i] = (m[0][i] == '0') ? 0 : 1;
            if(d[i] > max) max = d[i];
        }
        //循环
        for(int l = 1; l < m_size; l++) //从第1行开始
        {
            int preNode = d[0];
            d[0] = (m[l][0] == '0') ? 0 : 1;
            for(int j = 1; j < m[0].size(); j++)
            {
                if(m[l][j] == '0')
                {
                    preNode = d[j];
                    d[j] = 0;
                }
                else //m[l][j] = 1时
                {
                    int temp = min(preNode, d[j-1], d[j]);//d[l-1][j-1], d[l][j-1], d[l-1][j]
                    preNode = d[j];
                    d[j] = temp + 1;
                    if(d[j] > max)
                    {
                        max = d[j];
                    }
                }
            }
        }
        delete d;
        return max*max;
    }




Maximal Square (leeCode)

标签:动态规划

原文地址:http://blog.csdn.net/fy_sun123/article/details/46347547

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!