-
Notifications
You must be signed in to change notification settings - Fork 0
/
Count pairs sum in matrices
86 lines (64 loc) · 1.99 KB
/
Count pairs sum in matrices
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package gfg;
//Count pairs sum in matrices
import java.io.*;
import java.util.*;
class GFG {
public static void main(String args[]) throws IOException {
BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(read.readLine());
while (t-- > 0) {
String input[] = read.readLine().split(" ");
int n = Integer.parseInt(input[0]);
int x = Integer.parseInt(input[1]);
int mat1[][] = new int[n][n];
for(int i = 0;i<n;i++){
input = read.readLine().split(" ");
for(int j = 0;j<n;j++){
mat1[i][j] = Integer.parseInt(input[j]);
}
}
int mat2[][] = new int[n][n];
for(int i = 0;i<n;i++){
input = read.readLine().split(" ");
for(int j = 0;j<n;j++){
mat2[i][j] = Integer.parseInt(input[j]);
}
}
Solution ob = new Solution();
System.out.println(ob.countPairs(mat1,mat2,n,x));
}
}
}
class Solution {
int countPairs(int mat1[][], int mat2[][], int n, int x) {
// code here
int r1 = 0;
int c1 = 0;
int r2 = n - 1;
int c2 = n - 1;
int count = 0;
while(r1 < n && r2 >= 0) {
int sum = mat1[r1][c1] + mat2[r2][c2];
if(sum == x) {
count++;
c1++;
c2--;
}
if(sum > x) {
c2--;
}
if(sum < x) {
c1++;
}
if(c1 == n) {
c1 = 0;
r1++;
}
if(c2 == -1) {
c2 = n - 1;
r2--;
}
}
return count;
}
}