Learn basic concept of c , c++ and python programming in regularcodes.com

Spread the post

Print 2-d array in spiral form

Given a 2d array or a matrix. write an efficient algorithm to print this 2d array in spiral form.

Example

Suppose following nodes are inserted on Given Array.

 1      2   3     4    5  20    21   22   23    6  19    32   33   24    7  18    31   34   25    8  17    30   35   26    9  16    29   28   27   10  15    14   13   12   11

Result: print this array in spiral form

 1      2   3     4    5  20    21   22   23    6  19    32   33   24    7  18    31   34   25    8  17    30   35   26    9  16    29   28   27   10  15    14   13   12   11

Output : [1 2 3 4 5 6 7 8 9 10 11 12 13 14 16 17 18 19 20 21 22 23 24 25 26 27 28 30 31 32 33 34 35 ].

Another example:

 1      2   3     4    5  19    32   33   24    7  18    31   34   25    8  17    30   35   26    9  16    29   28   27   10  15    14   13   12   11

Spiral Form presentation.

 1      2   3     4    5  19    32   33   24    7  18    31   34   25    8  17    30   35   26    9  16    29   28   27   10  15    14   13   12   11

Output : 1 2 3 4 5 7 8 9 10 11 12 13 14 15 16 17 18 19 32 33 24 25 26 27 28 29 30 31 34 35

Program for Print matrix in spiral from in c. iterative Solution time complexity O(n).


Output

Array data presentation.

Stack Areamainarray [7,5] [0][0] 1[0][1] 2[0][2] 3[0][3] 4[0][4] 5[1][0] 20[1][1] 21[1][2] 22[1][3] 23[1][4] 6[2][0] 19[2][1] 32[2][2] 33[2][3] 24[2][4] 7[3][0] 18[3][1] 31[3][2] 34[3][3] 25[3][4] 8[4][0] 17[4][1] 30[4][2] 35[4][3] 26[4][4] 9[5][0] 16[5][1] 29[5][2] 28[5][3] 27[5][4] 10[6][0] 15[6][1] 14[6][2] 13[6][3] 12[6][4] 11col (int) =0flag (int) =0i (int) =0j (int) =0row (int) =0size (int) =0status (int) =0temp (int) =0

Visualize process Try it Yourself

Submit your solution in comment.

Spread the post

Recommended Posts: