LeetCode 835. Image Overlap C++

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 <= A.length = A[0].length = B.length = B[0].length <= 30
  • 0 <= A[i][j], B[i][j] <= 1

Approach

  1. 题目大意是两张二进制图片A和B,问你A和B重叠部分中1s最多有多少,A可以上下左右移动。这道题挺有意思的,我们可以采取映射的方式计算最多有多少,因为我们可以把B中的1s当做A中1s平移后的结果,那么平移距离相同的都会装在同一个’盒子’里,这样我就可以很容易的计算最多有多少,看代码思路会更加清晰。

Code

class Solution {
public:
	int largestOverlap(vector>& A, vector>& B) {
		int n = B.size();
		vector>count(n * 2 + 1, vector(n * 2 + 1, 0));
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < n; j++) {
				if (A[i][j] == 1) {
					for (int k = 0; k < n; k++) {
						for (int l = 0; l < n; l++) {
							if (B[k][l] == 1) {
								count[i - k + n][j - l + n]++;
							}
						}
					}
				}
			}
		}
		int maxn = 0;
		for (vector &cou : count) {
			for (int &c : cou) {
				maxn = max(maxn, c);
			}
		}
		return maxn;
	}
};

你可能感兴趣的:(Array)