#include <iostream> #include <vector> using namespace std; // A divide and conquer method to search a given key in mat[] // in rows from fromRow to toRow and columns from fromCol to toCol bool search(const vector<vector<int>>& mat, int fromRow, int toRow, int fromCol, int toCol, int key) { if (fromRow > toRow || fromCol > toCol) return false; int i = fromRow + (toRow - fromRow) / 2; int j = fromCol + (toCol - fromCol) / 2; if (mat[i][j] == key) { return true; } // Right-up quarter (Always Searched) if ((i != toRow || j != fromCol) && search(mat, fromRow, i, j, toCol, key)) return true; // Special case for 1x2 matrix if (fromRow == toRow && fromCol + 1 == toCol) { if (mat[fromRow][toCol] == key) return true; } if (mat[i][j] < key) { // Search lower horizontal return (i + 1 <= toRow && search(mat, i + 1, toRow, fromCol, toCol, key)); } else { // Search left vertical return (j - 1 >= fromCol && search(mat, fromRow, toRow, fromCol, j - 1, key)); } return false; } // Driver code int main() { vector<vector<int>> mat = { {10, 20, 30, 40}, {15, 25, 35, 45}, {27, 29, 37, 48}, {32, 33, 39, 50} }; int key = 50; if (search(mat, 0, mat.size() - 1, 0, mat[0].size() - 1, key)) cout << "Key " << key << " found\n"; else cout << "Key " << key << " not found\n"; return 0; }