-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Spiral_Matrix.c
118 lines (95 loc) · 1.92 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
/*Spiral Matrix
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
*/
#include <stdio.h>
void spiral_matrix(int[][10], int, int);
int main()
{
int ROW, COLUMN, is_null = 0;
printf("Enter Row: ");
scanf("%d", &ROW);
printf("Enter column: ");
scanf("%d", &COLUMN);
int matrix[10][10];
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");
}
}
spiral_matrix(matrix, ROW, COLUMN);
}
return 0;
}
// Prints the spiral matrix of the given matrix
void spiral_matrix(int matrix[][10], int ROW, int COLUMN)
{
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++;
}
}
}
/*
Sample Output
Enter Rows:2
Enter Column: 2
1 2
3 4
Entered Matrix:
1 2
3 4
Spiral Order of the Matrix: 1 2 4 3
Time Complexity: O(ROW*COLUMN)
Space Complexity:O(1).
*/