zoukankan      html  css  js  c++  java
  • 835. Image Overlap

    Two images A and B are given, represented as binary, square matrices of the same size.  (A binary matrix has only 0s and 1s as values.)

    We translate one image however we choose (sliding it left, right, up, or down any number of units), and place it on top of the other image.  After, the overlap of this translation is the number of positions that have a 1 in both images.

    (Note also that a translation does not include any kind of rotation.)

    What is the largest possible overlap?

    Example 1:

    Input: A = [[1,1,0],
                [0,1,0],
                [0,1,0]]
           B = [[0,0,0],
                [0,1,1],
                [0,0,1]]
    Output: 3
    Explanation: We slide A to right by 1 unit and down by 1 unit.

    Notes: 

    1. 1 <= A.length = A[0].length = B.length = B[0].length <= 30
    2. 0 <= A[i][j], B[i][j] <= 1

    Approach #1: Array. [Java]

    class Solution {
        public int largestOverlap(int[][] A, int[][] B) {
            int N = A.length;
            List<Integer> LA = new ArrayList<>();
            List<Integer> LB = new ArrayList<>();
            HashMap<Integer, Integer> count = new HashMap<>();
            for (int i = 0; i < N * N; ++i) if (A[i/N][i%N] == 1)
                LA.add(i / N * 100 + i % N);
            for (int i = 0; i < N * N; ++i) if (B[i/N][i%N] == 1)
                LB.add(i / N * 100 + i % N);
            for (int i : LA) for (int j : LB)
                count.put(i-j, count.getOrDefault(i-j, 0) + 1);
            int res = 0;
            for (int i : count.values()) res = Math.max(res, i);
            return res;
        }
    }
    

      

    Analysis:

    Assume index in A and B is [0, N*N-1]

    Loop on A, if value == 1, save a coordinates i / N * 100 + i % N to LA.

    Loop on B, if value == 1, save a coordinates i / N * 100 + i % N to LB.

    Loop on combination (i, j) of LA and LB, increase count[i-j] by 1.

    If we slid to make A[i] orverlap B[j], we can get 1 point.

    Loop on count and return max values.

    Time Complexity:

    O(N^2) for preparing, and O(AB) for loop.

    O(AB + N^2)

    Reference:

    https://leetcode.com/problems/image-overlap/discuss/130623/C%2B%2BJavaPython-Straight-Forward

    永远渴望,大智若愚(stay hungry, stay foolish)
  • 相关阅读:
    nginx模块学习——nginx_http_push_module模块深入讲解和聊天室实现
    常见的qq在线客服代码
    MongoDB数据库介绍及安装(一)
    Python 创建类
    Python backup脚本
    Python 类的初始化小案例
    Python 类实例化
    Python 类初始化__init__
    ObjC(ObjectiveC): NSString应该用initWithFormat? 还是 stringWithFormat?
    NSUserDefaults
  • 原文地址:https://www.cnblogs.com/h-hkai/p/10669690.html
Copyright © 2011-2022 走看看