Advertisement
alisadafi

Matrix-Search-D&C

Nov 9th, 2023
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.62 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. using namespace std;
  5.  
  6. pair<int, int> find(vector<vector<int>>& X, int k, int top_left_i, int top_left_j, int bottom_right_i, int bottom_right_j) {
  7.     int m_i = (top_left_i + bottom_right_i) / 2;
  8.     int m_j = (top_left_j + bottom_right_j) / 2;
  9.  
  10.     if (X[m_i][m_j] == k) {
  11.         return make_pair(m_i, m_j);
  12.     }
  13.  
  14.     if (top_left_i == bottom_right_i && top_left_j == bottom_right_j) {
  15.         return make_pair(-1, -1);  // not found
  16.     }
  17.  
  18.     if (top_left_i > bottom_right_i || top_left_j > bottom_right_j) {
  19.         return make_pair(-1, -1);  // not found
  20.     }
  21.  
  22.     if (X[m_i][m_j] > k) {
  23.         pair<int, int> pos = find(X, k, top_left_i, top_left_j, m_i - 1, m_j - 1);
  24.         if (pos != make_pair(-1, -1)) {
  25.             return pos;
  26.         }
  27.  
  28.         pos = find(X, k, m_i, top_left_j, bottom_right_i, m_j - 1);
  29.         if (pos != make_pair(-1, -1)) {
  30.             return pos;
  31.         }
  32.  
  33.         pos = find(X, k, top_left_i, m_j, m_i - 1, bottom_right_j);
  34.         if (pos != make_pair(-1, -1)) {
  35.             return pos;
  36.         }
  37.     }
  38.     else {
  39.         pair<int, int> pos = find(X, k, m_i + 1, m_j + 1, bottom_right_i, bottom_right_j);
  40.         if (pos != make_pair(-1, -1)) {
  41.             return pos;
  42.         }
  43.  
  44.         pos = find(X, k, m_i + 1, top_left_j, bottom_right_i, m_j);
  45.         if (pos != make_pair(-1, -1)) {
  46.             return pos;
  47.         }
  48.  
  49.         pos = find(X, k, top_left_i, m_j + 1, m_i, bottom_right_j);
  50.         if (pos != make_pair(-1, -1)) {
  51.             return pos;
  52.         }
  53.     }
  54.  
  55.     return make_pair(-1, -1);  // not found
  56. }
  57.  
Tags: D&C
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement