Spirally traversing a matrix | Practice | GeeksforGeeks

Given a matrix of size r*c. Traverse the matrix in spiral form.
Example 1:
Input:
r = 4, c = 4
matrix[][] = {{1, 2, 3, 4},
           {5, 6, 7, 8},
           {9, 10, 11, 12},
           {13, 14, 15,16}}
Output: 
1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10
Explanation:

Example 2:
Input:
r = 3, c = 4  
matrix[][] = {{1, 2, 3, 4},
           {5, 6, 7, 8},
           {9, 10, 11, 12}}
Output: 
1 2 3 4 8 12 11 10 9 5 6 7
Explanation:
Applying same technique as shown above, 
output for the 2nd testcase will be 
1 2 3 4 8 12 11 10 9 5 6 7.


Your Task:
You dont need to read input or print anything. Complete the function spirallyTraverse() that takes matrix, r and c as input parameters and returns a list of integers denoting the spiral traversal of matrix. 

Expected Time Complexity: O(r*c)
Expected Auxiliary Space: O(r*c), for returning the answer only.

Constraints:
1 <= r, c <= 100
0 <= matrixi <= 100
0
cuongphanin 6 hours
//java 9/7/22 12:26AM
static ArrayList<Integer> spirallyTraverse(int matrix[][], int r, int c)   {       ArrayList<Integer> res=new ArrayList<Integer>();      int min=Math.min(r,c);      int time=(int)Math.ceil(1.0*min/2);      int k=0;           while(time!=k){         //top         for(int t=k;t<c-k;t++){             res.add(matrix[k][t]);         }         //right         for(int ri=k+1;ri<r-k;ri++){             res.add(matrix[ri][c-k-1]);         }         //bottom         for(int b=c-2-k;b>=k;b--){             if(r-k-1==k) break;//same with top             res.add(matrix[r-k-1][b]);         }         //left           for(int l=r-2-k;l>k;l--){             if(c-k-1==k) break;//same with right             res.add(matrix[l][k]);         }                 k++;     }      return res;         }
0
ntt45419117 hours ago
// C++ 0.08s
void outer(vector<vector<int>>& mat,int r, int c, int b, vector<int>& ans){
     for(int i{b};i<c-b;i++) ans.push_back(mat[b][i]);
     for(int i{b+1};i<r-b;i++) ans.push_back(mat[i][c-b-1]);
      
     if(r-b-1==b) return; 
     for(int i{c-b-2}; i>=b;i--) ans.push_back(mat[r-b-1][i]);
      
     if(b==c-b-1) return;
     for(int i{r-b-2}; i>b;i--) ans.push_back(mat[i][b]);
   }
    


 vector<int> spirallyTraverse(vector<vector<int> > matrix, int r, int c) 
    {
        vector<int> ans;
        int b=0,limit=min(r,c);
        if(limit & 1) limit++;

        while(b<limit/2) outer(matrix,r,c,b++,ans);
        return ans;
    }
0
arnab_deb_211 day ago
vector<int> spirallyTraverse(vector<vector<int> > matrix, int r, int c)    {       vector<int> result;       int count = r*c;       int i,j,k,l;       int row = 0;       int col = c;       int m = 0;       while(count>0){           for(k=row;k<col;k++){               result.push_back(matrix[row][k]);               count--;           }           if(count==0)               break;           row++;           for(j=row;j<=r-row;j++){               result.push_back(matrix[j][col-1]);               count--;           }           if(count==0)               break;           col--;           for(l=col-1;l>=row-1;l--){               result.push_back(matrix[j-1][l]);               count--;           }           if(count==0)            break;           j--;           l++;           for(i=j-1;i>=row;i--){               result.push_back(matrix[i][l]);               count--;           }       }       return result;   }
0
nitishmishra9372 days ago
Java Code
 
static ArrayList<Integer> spirallyTraverse(int matrix[][], int r, int c)
    {
        // code here 
        ArrayList<Integer> list = new ArrayList<Integer> ();
       
        int i = 0, j = 0;
        int maxI = r, maxJ = c;
        int minI = 0, minJ = 0;
        int count = 0, total = r*c;
        while(count < total) {
            while(j < maxJ && count < total) {
                list.add(matrix[i][j]);
                j++;
                ++count;
            }
            j--;
            maxJ--;
            i++;
            
            while(i < maxI && count < total) {
                list.add(matrix[i][j]);
                i++;
                ++count;
            }
            i--;
            maxI--;
            j--;
            
            while(j >= minJ && count < total) {
                 list.add(matrix[i][j]);
                 j--;
                 ++count;
            }
            j++;
            minJ++;
            i--;
            
            while(i > minI && count < total) {
                 list.add(matrix[i][j]);
                 i--;
                 ++count;
            }
            i++;
            minI++;
            j++;
        }
        return list;
    }
0
premkumar352 days ago
// JAVA CODE
 
class Solution{   //Function to return a list of integers denoting spiral traversal of matrix.   static ArrayList<Integer> spirallyTraverse(int matrix[][], int r, int c)   {       int nr = r; int nl = 0; int mr = c; int ml = 0; int i = 0; int j = 0; int ki = 0; int kj = 1;  ArrayList<Integer> al = new ArrayList<>();  while(i<nr && i>=nl && j>=ml && j<mr) {  al.add(matrix[i][j]);  i=i+ki;  j=j+kj;  if(i == nl && j == mr) {   kj = 0;   ki = 1;   nl++;   i++;   j--;  }  else if(i == nr && j == mr-1) {   mr--;   kj = -1;   ki = 0;   j--;   i--;  }  else if(i == nr-1 && j == ml-1) {   nr--;   i--;   j++;   ki = -1;   kj = 0;  }  else if (i == nl-1 && j == ml) {   ki = 0;   kj = 1;   ml++;   i++;   j++;  }   }  return al;   }}
0
pandeyshrey242 days ago
// HERE IS THE CODE WHICH I THINK IS MORE EXPLAINABLE 
 
   // code here        vector<int>ans;       int cnt=0;       int total= r*c;              int row_start=0,row_end=r-1,col_start=0,col_end=c-1;              while(cnt<total){           //for row start                      for(int col=col_start;col<=col_end&& cnt<total;col++){               ans.push_back(matrix[row_start][col]);               cnt++;           }           row_start++;           //for col end           for(int row=row_start;row<=row_end&&cnt<total;row++){               ans.push_back(matrix[row][col_end]);               cnt++;           }           col_end--;                      //for row end           for(int col=col_end;col>=col_start&&cnt<total;col--){               ans.push_back(matrix[row_end][col]);               cnt++;           }           row_end--;                      //for col start             for(int row=row_end;row>=row_start&&cnt<total;row--){               ans.push_back(matrix[row][col_start]);               cnt++;           }           col_start++;       }       return ans;
0
lovemurari20183 days ago
//c++ easy solution
//total time taken  0.08/1.07
 vector<int> spirallyTraverse(vector<vector<int> > matrix, int r, int c)    {       // code here         vector<int> ans;       int cnt = 0;       int total = r * c;              int startingRow = 0;       int startingClm = 0;       int endingRow = r-1;       int endingClm = c-1;              while(cnt<total){           for(int index = startingClm; index <= endingClm && cnt < total; index++){               ans.push_back(matrix[startingRow][index]);               cnt++;           }           startingRow++;                      for(int index = startingRow; index <= endingRow && cnt < total ; index++ ){               ans.push_back(matrix[index][endingClm]);                 cnt++;           }           endingClm--;                      for(int index = endingClm; index>= startingClm && cnt< total; index--){               ans.push_back(matrix[endingRow][index]);                 cnt++;           }           endingRow--;                      for(int index = endingRow; index>=startingRow && cnt< total ; index--){               ans.push_back(matrix[index][startingClm]);                 cnt++;           }           startingClm++;       }       return ans;      }
0
madhavisharma21524 days ago
java solution. I have added comments for better understanding.. good luck..  Note that target is the limit to which that particular column or row goes up..!
 
       int target_up=0;       int target_down=arr.length-1;       int target_right=arr[0].length-1;       int target_left=0;       int mat=r*c;       int cnt=0;       ArrayList<Integer> list=new ArrayList<>();       while(cnt<mat)       {           //top           //i=target_up           for(int j=target_left;j<=target_right&&cnt<mat;j++)           {               list.add(arr[target_up][j]);               cnt++;           }           target_up++;                      //right           //j=target_right           for(int i=target_up;i<=target_down&&cnt<mat;i++)           {               list.add(arr[i][target_right]);               cnt++;           }           target_right--;                      //bottom           //i=target_bottom           for(int j=target_right;j>=target_left&&cnt<mat;j--)           {               list.add(arr[target_down][j]);               cnt++;           }           target_down--;                      //left           //i=target_left           for(int i=target_down;i>=target_up&&cnt<mat;i--)           {               list.add(arr[i][target_left]);               cnt++;           }           target_left++;       }       return list;
0
manoranjan201019995 days ago
// code here        vector<int>vec;       int top=0,left=0,bot=r-1,right=c-1;       while(top<=bot&&left<=right)       {           //   Top - Row            for(int i=left;i<=right;i++)           {               vec.push_back(matrix[top][i]);           }           top++;           //  Right Col           for(int i=top;i<=bot;i++)           {               vec.push_back(matrix[i][right]);           }           right--;           // Bottom Row REverse Order           if(top<=bot)           {               for(int i=right;i>=left;i--)               {                   vec.push_back(matrix[bot][i]);                                  }               bot--;           }           // left Col Reverse           if(left<=right)           {               for(int i=bot;i>=top;i--)               {                   vec.push_back(matrix[i][left]);               }               left++;           }                                        }       return vec;
+1
hjangid005 days ago
vector<int> spirallyTraverse(vector<vector<int> > matrix, int r, int c)    {       int top=0;       int bottom=r-1;       int left=0;       int right=c-1;       vector<int>v;       while(1){           if(left>right)break;           for(int i=left;i<=right;i++){               v.push_back(matrix[top][i]);           }           top++;           if(top>bottom)break;           for(int i=top;i<=bottom;i++){               v.push_back(matrix[i][right]);           }           right--;           if(left>right)break;           for(int i=right;i>=left;i--){               v.push_back(matrix[bottom][i]);           }           bottom--;           if(top>bottom)break;           for(int i=bottom;i>=top;i--){               v.push_back(matrix[i][left]);           }           left++;       }       return v;   }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested 
                                    against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code.
                                    On submission, your code is tested against multiple test cases consisting of all
                                        possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as
                                        the final solution code.
You can view the solutions submitted by other users from the submission tab.
Make sure you are not using ad-blockers.
Disable browser extensions.
We recommend using latest version of your browser for best experience.
Avoid using static/global variables in coding problems as your code is tested 
                                against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases in coding problems does not guarantee the 
                                correctness of code. On submission, your code is tested against multiple test cases
                                    consisting of all possible corner cases and stress constraints.