Here is a simple solution to your problem:
Keep a 2D array(checkIfVisited
) of the same size(all cells initialized to 0
) of that your array, in order to keep track of the cells that are already visited. If (i,j)
is 1
then it means that the cell in the original has already been visited.
We iterate the whole array spirally with the help of the dir
variable which keeps track of which direction we are currently traversing.
dir
= 0
means moving downwards, 1
means moving rightwards, 2
means moving upwards, 3
means moving leftwards.
We change directions when either i
and j
goes out of limits or when the next cell to be traversed has already been traversed before by doing a lookup from the checkIfVisited
array.
I have a simple C++ implementation of the above algorithm:
#include <iostream>
using namespace std;
int main()
{
int arr[5][5] = {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};
int checkIfVisited[5][5] = {0,0,0,0,0,
0,0,0,0,0,
0,0,0,0,0,
0,0,0,0,0,
0,0,0,0,0};
int i,j,dir,countVisited;
dir = 0;
countVisited = 0;
i = 0;
j = 0;
while(countVisited<5*5)
{
cout<<arr[i][j]<<" ";
checkIfVisited[i][j]=1;
if(dir==0)
{
countVisited++;
if(i+1>4 || checkIfVisited[i+1][j]==1){
dir=1;
j++;
}
else
i++;
}
else if(dir==1)
{
countVisited++;
if(j+1>4 || checkIfVisited[i][j+1]==1){
dir=2;
i--;
}
else
j++;
}
else if(dir==2)
{
countVisited++;
if(i-1<0 || checkIfVisited[i-1][j]==1){
dir=3;
j--;
}
else
i--;
}
else
{
countVisited++;
if(j-1<0 || checkIfVisited[i][j-1]==1){
dir=0;
i++;
}
else
j--;
}
}
return 0;
}
Output: 10 15 20 25 30 31 32 33 34 29 24 19 14 13 12 11 16 21 26 27 28 23 18 17 22