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 04 nthEleSpiralMatrix.cpp #57

Merged
merged 1 commit into from
May 13, 2021
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
40 changes: 40 additions & 0 deletions 04 Matrix/04 nthEleSpiralMatrix.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
# Find nth element in a spiral matrix

int findK(int matrix[MAX][MAX], int row, int col, int k)
{

int x = 0;

int rs = 0, re = row-1, cs = 0, ce = col-1, tot = row*col;

while (x < (row*col)) {
for (int j = cs; j <= ce && x < tot; ++j) {
x++;
if (x == k) {
return matrix[rs][j];
}
}
rs++;
for (int i = rs; i <= re && x < tot; ++i) {
x++;
if (x == k) {
return matrix[i][ce];
}
}
ce--;
for (int j = ce; j >= cs && x < tot; --j) {
x++;
if (x == k) {
return matrix[re][j];
}
}
re--;
for (int i = re; i >= rs && x < tot; --i) {
x++;
if (x == k) {
return matrix[i][cs];
}
}
cs++;
}
}