Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create Staircase Search in a 2D Matrix #1

Merged
merged 1 commit into from
Oct 12, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions search/Staircase Search in a 2D Matrix
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
#include <bits/stdc++.h>
using namespace std;

bool staircaseSearch(vector<vector<int>>& matrix, int target) {
int rows = matrix.size();
int cols = matrix[0].size();
int row = 0, col = cols - 1;

while (row < rows && col >= 0) {
if (matrix[row][col] == target) {
return true;
} else if (matrix[row][col] > target) {
col--;
} else {
row++;
}
}
return false;
}

int main() {
vector<vector<int>> matrix = {
{1, 4, 7, 11},
{2, 5, 8, 12},
{3, 6, 9, 16},
{10, 13, 14, 17}
};
int target = 8;
if (staircaseSearch(matrix, target))
cout << "Element found." << endl;
else
cout << "Element not found." << endl;

return 0;
}