Skip to content

Commit 62eef08

Browse files
Create Staircase Search in a 2D Matrix
1 parent 136e6c0 commit 62eef08

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
4+
bool staircaseSearch(vector<vector<int>>& matrix, int target) {
5+
int rows = matrix.size();
6+
int cols = matrix[0].size();
7+
int row = 0, col = cols - 1;
8+
9+
while (row < rows && col >= 0) {
10+
if (matrix[row][col] == target) {
11+
return true;
12+
} else if (matrix[row][col] > target) {
13+
col--;
14+
} else {
15+
row++;
16+
}
17+
}
18+
return false;
19+
}
20+
21+
int main() {
22+
vector<vector<int>> matrix = {
23+
{1, 4, 7, 11},
24+
{2, 5, 8, 12},
25+
{3, 6, 9, 16},
26+
{10, 13, 14, 17}
27+
};
28+
int target = 8;
29+
if (staircaseSearch(matrix, target))
30+
cout << "Element found." << endl;
31+
else
32+
cout << "Element not found." << endl;
33+
34+
return 0;
35+
}

0 commit comments

Comments
 (0)