1. Beranda
  2. miscellaneous questions
  3. Print matrix in spiral form

Print matrix in spiral form

Question : The question is pretty much clear that we have to print the matrix in spiral form. So for this we will take four pointers pointing to top, down, left & right of the given matrix. Next we will take dir variable which will basically store the direction that is :

 

dir = 0 means from left to right

dir = 1 means from top to down

dir = 2 means from right to left

dir = 3 means from down to top

 

Rest you can easily figure out by below images :
 

 

#include<bits/stdc++.h>
using namespace std;

void show(int row, int col, int a[r][c])
{
int dir = 0, top = 0, down = r-1, left = 0, right = c-1, i, j;
while(left <= right && top <= down)
{
if(dir == 0)
{
for(i = top; i <= right; i++) cout << a[top][i] << " ";
top++;
}
else if(dir == 1)
{
for(i = top; i <= down; i++) cout << a[i][right] << " ";
right--;
}
else if(dir == 2)
{
for(i = right; i >= left; i--) cout << a[down][i] << " ";
down--;
}
else if(dir == 3)
{
for(i = down; i >= top; i--) cout << a[i][left] << " ";
left++;
dir = -1;
}
dir++;
}
}

int main()
{
int a[r][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} };
show(r, c, a);
return 0;
}

 

Pic Credits : GeeksforGeeks

Video reference : Tech Dose

Tentang blog ini

Syahdan Dev, dikelola Syahdan Filsafan

Software engineer dan pengembang di balik APIPedia. Blog ini membahas AI, Claude Code, dan rekayasa perangkat lunak secara praktis, dalam bahasa Indonesia.

Tidak ada komentar: