forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Spiral_Matrix.c
123 lines (101 loc) · 1.9 KB
/
Spiral_Matrix.c
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
/*
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
Sample case 1:
Input:
Enter Rows:2
Enter Column: 2
1
2
3
4
Output:
Entered Matrix:
1 2
3 4
Spiral Order of the Matrix: 1 2 4 3
Sample Case 2:
Input:
Enter Rows:2
Enter Column: 2
0
0
0
0
Output:
Null Matrix
Time Complexity: O(ROW*COLUMN)
Space Complexity:O(1).
*/
#include <stdio.h>
int main()
{
int ROW, COLUMN, is_null = 0;
printf("Enter Row: ");
scanf("%d",&ROW);
printf("Enter column: ");
scanf("%d",&COLUMN);
int matrix[ROW][COLUMN];
for(int i=0; i < ROW; i++)
{
for(int j = 0; j <COLUMN; j++)
{
scanf("%d",&matrix[i][j]);
if(matrix[i][j] == 0)
is_null++;
}
}
if(is_null == ROW*COLUMN)
{
printf("\nNull Matrix\n");
}
else
{
printf("Entered Matrix:\n");
for(int i = 0; i < ROW; i++)
{
printf("\n");
for(int j = 0; j < COLUMN; j++)
{
printf("%d",matrix[i][j]);
printf("\t");
}
}
printf("\n\nSpiral Order Of the Matrix: \t");
int i;
int first_row = 0, first_column = 0;
while (first_row < ROW && first_column < COLUMN)
{
/* Print the first row from the remaining rows */
for (i = first_column; i < COLUMN; ++i)
{
printf("%d ", matrix[first_row][i]);
}
first_row++;
/* Print the last column from the remaining columns */
for (i = first_row; i < ROW; ++i)
{
printf("%d ", matrix[i][COLUMN - 1]);
}
COLUMN--;
/* Print the last row from the remaining rows */
if (first_row < ROW)
{
for (i = COLUMN - 1; i >= first_column; --i)
{
printf("%d ", matrix[ROW - 1][i]);
}
ROW--;
}
/* Print the first column from the remaining columns */
if (first_column < COLUMN)
{
for (i = ROW - 1; i >= first_row; --i)
{
printf("%d ", matrix[i][first_column]);
}
first_column++;
}
}
}
return 0;
}