|
| 1 | +class Solution { |
| 2 | + public int largestOverlap(int[][] img1, int[][] img2) { |
| 3 | + int R1 = img1.length; |
| 4 | + int R2 = img2.length; |
| 5 | + int C1 = img1[0].length; |
| 6 | + int C2 = img2[0].length; |
| 7 | + int max = Integer.MIN_VALUE; |
| 8 | + |
| 9 | + //Slide one image on other image. |
| 10 | + for(int r=0; r<R1+R2-1; r++){ |
| 11 | + int i = R1-1 + Math.min(0, R2-1-r); |
| 12 | + int x = r + Math.min(0, R2-1-r); |
| 13 | + for(int c=0; c<C1+C2-1; c++){ |
| 14 | + int j = C1-1 + Math.min( 0 , C2-1-c); |
| 15 | + int y = c + Math.min(0 , C2-1-c); |
| 16 | + max = Math.max(max, overlap(img1,img2,i,j,x,y)); |
| 17 | + } |
| 18 | + } |
| 19 | + return max; |
| 20 | + } |
| 21 | + |
| 22 | + //Compares two matrices from give coordinates to LEFT-TOP |
| 23 | + int overlap(int[][] img1, int[][] img2, int i1,int j1, int i2, int j2){ |
| 24 | + int count = 0; |
| 25 | + for(int i=i1,x=i2; i>=0 && x>=0; i--,x--){ |
| 26 | + for(int j=j1, y=j2; j >=0 && y>=0 ; j--,y--){ |
| 27 | + if(img1[i][j] == img2[x][y]){ |
| 28 | + if(img1[i][j]==1) |
| 29 | + count++; |
| 30 | + } |
| 31 | + } |
| 32 | + } |
| 33 | + //System.out.println("[" + i1+" , "+j1+"] ["+ i2 + " , "+j2+" ]" + "===" + count); |
| 34 | + return count; |
| 35 | + } |
| 36 | +} |
0 commit comments