835. Image Overlap

2018/10/06 leetcode 共 1146 字,约 4 分钟

title

problem link

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.

solution

对direction计数, dir最大的就是想要的

class Solution {
public:
	int largestOverlap(vector<vector<int>>& A, vector<vector<int>>& B) {
		vector<vector<int>> dir(A.size() * 2 + 1, vector<int>(A.size() * 2 + 1, 0));
		int N = A.size();
		if (N == 0) return 0;
		for (int i = 0; i < A.size(); i++) {
			for (int j = 0; j < A.size(); j++) {
				if (A[i][j] == 1) {
					for (int i2 = 0; i2 < B.size(); i2++) {
						for (int j2 = 0; j2 < B.size(); j2++) {
							if (B[i2][j2] == 1) {
								dir[i - i2 + N][j - j2 + N]++;
							}
						}
					}
				}
			}
		}
		int res = 0;
		for (auto& it : dir) {
			for (auto& k : it) {
				res = max(res, k);
			}
		}
		return res;
	}
};

Search

    Table of Contents