-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path9.1_two_dimensional_array.cpp
104 lines (92 loc) · 1.94 KB
/
9.1_two_dimensional_array.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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#include<iostream>
using namespace std;
/*
int main(){
int n,m;
cin>>n>>m;
int a[n][m];
for(int i=0; i<n; i++){
for(int j=0; j<m; j++){
cin>>a[i][j];
}
}
for(int i=0; i<n; i++){
for(int j=0; j<m; j++){
cout<<a[i][j]<<" ";
}
cout<<"\n";
}
return 0;
}
//searching a element in 2-D array
int main(){
int x;
cin>>x;
int n,m;
cin>>n>>m;
int a[n][m];
for(int i=0; i<n; i++){
for(int j=0; j<m; j++){
cin>>a[i][j];
}
}
for(int i=0; i<n; i++){
for(int j=0; j<m; j++){
cout<<a[i][j]<<" ";
}
cout<<"\n";
}
bool flag=false;
for(int i=0; i<n; i++){
for(int j=0; j<m; j++){
if(a[i][j]==x){
cout<<"Element is found:"<<i+1<<" "<<j+1<<endl;
flag=true;
}
}
}
if (flag==false){
cout<<"Element is not found\n";
}
return 0;
}
*/
// spiral order matrix Traversal
signed main(){
int n,m;
cin>>n>>m;
int a[n][m];
for(int i=0; i<n; i++){
for(int j=0; j<m; j++){
cin>>a[i][j];
}
}
int row_start=0, row_end=n-1, column_start=0, column_end=m-1;
while(row_start <= row_end && column_start <= column_end){
//for row start
for(int col=column_start; col<=column_end; col++){
cout<<a[row_start][col]<<" ";
}
row_start++;
//for column end
for(int row=row_start; row <= row_end; row++){
cout<<a[row][column_end]<<" ";
}
column_end--;
if(row_start<=row_end){
// for row end
for(int col=column_end; col>=column_start; col--){
cout<<a[row_end][col]<<" ";
}
}
row_end--;
if(column_start<=column_end){
//for column start
for(int row=row_end; row>=row_start; row--){
cout<<a[row][column_start]<<" ";
}
}
column_start++;
}
return 0;
}