9 {
10 int rows = mat.size();
11 int cols = mat[0].size();
12 vector<pair<int, int>> locations(rows * cols + 1);
13 vector<int> counts_x(rows, 0);
14 vector<int> counts_y(cols, 0);
15
16
17 for (int i = 0; i < rows; ++i)
18 {
19 for (int j = 0; j < cols; ++j)
20 {
21 locations[mat[i][j]] = {i, j};
22 }
23 }
24
25
26 for (int i = 0; i < (int)arr.size(); ++i)
27 {
28 auto [x, y] = locations[arr[i]];
29 counts_x[x]++;
30 counts_y[y]++;
31 if (counts_x[x] == cols || counts_y[y] == rows)
32 return i;
33 }
34 return -1;
35 }