-
Notifications
You must be signed in to change notification settings - Fork 163
/
Copy pathspiralTraversalOfMatrix.cpp
43 lines (39 loc) · 1020 Bytes
/
spiralTraversalOfMatrix.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include<bits/stdc++.h>
using namespace std;
int findK(vector<vector<int>> &a, int n, int m, int k)
{
int top=0,down=n-1,left=0,right=m-1;
int d=0;
int counter=0;
while(top<=down && left<=right)
{
for(int i=left;i<=right && counter<k;i++)
{
if(counter==k-1)
return a[top][i];
counter++;
}
top+=1;
for(int i=top;i<=down && counter<k;i++)
{
if(counter==k-1)
return a[i][right];
counter++;
}
right-=1;
for(int i=right;i>=left && counter<k;i--)
{
if(counter==k-1)
return a[down][i];
counter++;
}
down-=1;
for(int i=down;i>=top && counter<k;i--)
{
if(counter==k-1)
return a[i][left];
counter++;
}
left+=1;
}
}