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

Submatrix Sum

时间:2016-07-23 00:27:44      阅读:220      评论:0      收藏:0      [点我收藏+]

标签:

Given an integer matrix, find a submatrix where the sum of numbers is zero. Your code should return the coordinate of the left-up and right-down number.

Subarray Sum的follow up。求二维矩阵上和为0的submatrix. 

这题暴力解法枚举左上两坐标,右下两坐标,求中间和。复杂度为O(n^6)。太高。

比较好的办法是枚举开始行和结束行,之后以subarray sum的思路,用hashmap发现左边界和右边界。

为了高效求的开始行和结束行之间每一列的sum,可以先求得以(0,0)开始,右下坐标结束的submatrix sum。复杂度为O(m,n)。这一点比较神奇。

总体复杂度为O(n^2*m).代码如下:

class Solution:
    # @param {int[][]} matrix an integer matrix
    # @return {int[][]} the coordinate of the left-up and right-down number
    def submatrixSum(self, matrix):
        """
        1.enumerate the down-right corner, compute the sum firstly
        2.enumerate the begin line and end line, find the submatrix just like the subarry(traverse the right line) 
        """
        res = [[0,0],[0,0]]
        if not matrix or not matrix[0]:
            return res
        m = len(matrix)
        n = len(matrix[0])
        
        presum = [[0] * (n+1) for i in xrange(m+1)]
        for i in xrange(m):  #求以(0,0)开始,右下坐标结束的子矩阵的复杂度。
            for j in xrange(n):
                presum[i+1][j+1] = presum[i][j+1] + presum[i+1][j] - presum[i][j] + matrix[i][j]
        for l in xrange(m):
            for h in xrange(l+1,m+1):
                hash = {}
                for r in xrange(0, n+1):
                    diff = presum[h][r] - presum[l][r]
                    if diff not in hash:
                        hash[diff] = r
                    else:
                        res[0][0] = l
                        res[0][1] = hash[diff]
                        res[1][0] = h - 1
                        res[1][1] = r-1
                        
        return res

 

Submatrix Sum

标签:

原文地址:http://www.cnblogs.com/sherylwang/p/5697516.html

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