[Approach] Using Simulation by Visited Matrix - O(m*n) Time and O(m*n) Space
The idea is to simulate the spiral traversal by marking the cells that have already been visited. We can use a direction array to keep track of the movement (right, down, left, up) and change direction when we hit the boundary or a visited cell.
Step By Step Implementations:
Initialize a 2D array vis[][] to keep track of visited cells.
Use direction arrays dr and dc to represent right, down, left, and up movements.
Start from the top-left cell and follow the direction arrays to visit each cell.
Change direction when encountering a boundary or a visited cell.
Continue until all cells are visited.
C++
#include<iostream>#include<vector>usingnamespacestd;vector<int>spirallyTraverse(vector<vector<int>>&mat){intm=mat.size();intn=mat[0].size();vector<int>res;vector<vector<bool>>vis(m,vector<bool>(n,false));// Arrays to represent the changes // in row and column indices: // move right(0, +1), move down(+1, 0), // move left(0, -1), move up(-1, 0)// Change in row index for each directionvector<int>dr={0,1,0,-1};// Change in column index for each directionvector<int>dc={1,0,-1,0};// Initial position in the matrixintr=0,c=0;// Initial direction index (0 corresponds to 'right')intidx=0;for(inti=0;i<m*n;++i){res.push_back(mat[r][c]);vis[r][c]=true;// Calculate the next cell coordinates based on// current directionintnewR=r+dr[idx];intnewC=c+dc[idx];// Check if the next cell is within bounds and not// visitedif(0<=newR&&newR<m&&0<=newC&&newC<n&&!vis[newR][newC]){// Move to the next rowr=newR;// Move to the next columnc=newC;}else{// Change direction (turn clockwise)idx=(idx+1)%4;// Move to the next row according to new// directionr+=dr[idx];// Move to the next column according to new// directionc+=dc[idx];}}returnres;}intmain(){vector<vector<int>>mat={{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};vector<int>res=spirallyTraverse(mat);for(intnum:res){cout<<num<<" ";}return0;}
Java
importjava.util.ArrayList;importjava.util.List;classGfG{staticArrayList<Integer>spirallyTraverse(int[][]mat){intm=mat.length;intn=mat[0].length;ArrayList<Integer>res=newArrayList<>();boolean[][]vis=newboolean[m][n];// Change in row index for each directionint[]dr={0,1,0,-1};// Change in column index for each directionint[]dc={1,0,-1,0};// Initial position in the matrixintr=0,c=0;// Initial direction index (0 corresponds to 'right')intidx=0;for(inti=0;i<m*n;++i){// Add current element to result listres.add(mat[r][c]);// Mark current cell as visitedvis[r][c]=true;// Calculate the next cell coordinates based on// current directionintnewR=r+dr[idx];intnewC=c+dc[idx];// Check if the next cell is within bounds and not// visitedif(0<=newR&&newR<m&&0<=newC&&newC<n&&!vis[newR][newC]){// Move to the next rowr=newR;// Move to the next columnc=newC;}else{// Change direction (turn clockwise)idx=(idx+1)%4;// Move to the next row according to new// directionr+=dr[idx];// Move to the next column according to new// directionc+=dc[idx];}}returnres;}publicstaticvoidmain(String[]args){int[][]mat={{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};ArrayList<Integer>res=spirallyTraverse(mat);for(intnum:res){System.out.print(num+" ");}}}
Python
defspirallyTraverse(mat):m=len(mat)n=len(mat[0])res=[]vis=[[False]*nfor_inrange(m)]# Change in row index for each directiondr=[0,1,0,-1]# Change in column index for each directiondc=[1,0,-1,0]# Initial position in the matrixr,c=0,0# Initial direction index (0 corresponds to 'right')idx=0for_inrange(m*n):res.append(mat[r][c])vis[r][c]=True# Calculate the next cell coordinates based on# current directionnewR,newC=r+dr[idx],c+dc[idx]# Check if the next cell is within bounds and not# visitedif0<=newR<mand0<=newC<nandnotvis[newR][newC]:# Move to the next rowr,c=newR,newCelse:# Change direction (turn clockwise)idx=(idx+1)%4# Move to the next row according to new# directionr+=dr[idx]# Move to the next column according to new# directionc+=dc[idx]returnresif__name__=="__main__":mat=[[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]res=spirallyTraverse(mat)print(" ".join(map(str,res)))
C#
usingSystem;usingSystem.Collections.Generic;classGfG{staticList<int>spirallyTraverse(int[][]mat){intm=mat.Length;intn=mat[0].Length;List<int>res=newList<int>();bool[,]vis=newbool[m,n];// Arrays to represent the changes in row and column// indices: turn right(0, +1), turn down(+1, 0),// turn left(0, -1), turn up(-1, 0)int[]dr={0,1,0,-1};int[]dc={1,0,-1,0};// Initial position in the matrixintr=0,c=0;// Initial direction index (0 corresponds to// 'right')intidx=0;for(inti=0;i<m*n;++i){res.Add(mat[r][c]);vis[r,c]=true;// Calculate the next cell coordinates based on// current directionintnewR=r+dr[idx];intnewC=c+dc[idx];// Check if the next cell is within bounds and// not visitedif(newR>=0&&newR<m&&newC>=0&&newC<n&&!vis[newR,newC]){r=newR;c=newC;}else{// Change direction (turn clockwise)idx=(idx+1)%4;r+=dr[idx];c+=dc[idx];}}returnres;}staticvoidMain(){int[][]mat={newint[]{1,2,3,4},newint[]{5,6,7,8},newint[]{9,10,11,12},newint[]{13,14,15,16}};List<int>res=spirallyTraverse(mat);foreach(intnuminres)Console.Write(num+" ");}}
JavaScript
functionspirallyTraverse(mat){constm=mat.length;constn=mat[0].length;constres=[];constvis=Array.from({length:m},()=>Array(n).fill(false));// Arrays to represent the changes in row and column// indices: turn right(0, +1), turn down(+1, 0), turn// left(0, -1), turn up(-1, 0)constdr=[0,1,0,-1];constdc=[1,0,-1,0];// Initial position in the matrixletr=0,c=0;// Initial direction index (0 corresponds to 'right')letidx=0;for(leti=0;i<m*n;++i){// Add current element to result arrayres.push(mat[r][c]);// Mark current cell as visitedvis[r][c]=true;// Calculate the next cell coordinates based on// current directionconstnewR=r+dr[idx];constnewC=c+dc[idx];// Check if the next cell is within bounds and not// visitedif(newR>=0&&newR<m&&newC>=0&&newC<n&&!vis[newR][newC]){r=newR;c=newC;}else{// Change direction (turn clockwise)idx=(idx+1)%4;r+=dr[idx];c+=dc[idx];}}returnres;}// Driver Codeconstmat=[[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]];constres=spirallyTraverse(mat);console.log(res.join(" "));
Output
1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10
[Expected Approach] Using Boundary Traversal - O(m*n) Time and O(1) Space
We can print the matrix in a spiral order by dividing it into loops or boundaries. We print the elements of the outer boundary first, then move inward to print the elements of the inner boundaries.
Algorithm:
Define the boundaries of the matrix with variables top, bottom, left, and right.
Print the top row from left to right and increment top.
Print the right column from top to bottom and decrement right.
Check if boundaries have crossed; if not, print the bottom row from right to left and decrement bottom.
Print the left column from bottom to top and increment left.
Repeat until all boundaries are crossed.
Illustration:
C++
#include<iostream>#include<vector>usingnamespacestd;vector<int>spirallyTraverse(vector<vector<int>>&mat){intm=mat.size();intn=mat[0].size();vector<int>res;// Initialize boundariesinttop=0,bottom=m-1,left=0,right=n-1;// Iterate until all elements are storedwhile(top<=bottom&&left<=right){// store top row from left to rightfor(inti=left;i<=right;++i){res.push_back(mat[top][i]);}top++;// store right column from top to bottomfor(inti=top;i<=bottom;++i){res.push_back(mat[i][right]);}right--;// store bottom row from right to left (if exists)if(top<=bottom){for(inti=right;i>=left;--i){res.push_back(mat[bottom][i]);}bottom--;}// store left column from bottom to top (if exists)if(left<=right){for(inti=bottom;i>=top;--i){res.push_back(mat[i][left]);}left++;}}returnres;}intmain(){vector<vector<int>>mat={{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};vector<int>res=spirallyTraverse(mat);for(intele:res)cout<<ele<<" ";return0;}
Java
importjava.util.ArrayList;classGfG{staticArrayList<Integer>spirallyTraverse(int[][]mat){intm=mat.length;intn=mat[0].length;ArrayList<Integer>res=newArrayList<>();// Initialize boundariesinttop=0,bottom=m-1,left=0,right=n-1;// Iterate until all elements are printedwhile(top<=bottom&&left<=right){// Print top row from left to rightfor(inti=left;i<=right;++i){res.add(mat[top][i]);}top++;// Print right column from top to bottomfor(inti=top;i<=bottom;++i){res.add(mat[i][right]);}right--;// Print bottom row from right to left (if exists)if(top<=bottom){for(inti=right;i>=left;--i){res.add(mat[bottom][i]);}bottom--;}// Print left column from bottom to top (if exists)if(left<=right){for(inti=bottom;i>=top;--i){res.add(mat[i][left]);}left++;}}returnres;}// Driver Codepublicstaticvoidmain(String[]args){int[][]mat={{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};ArrayList<Integer>res=spirallyTraverse(mat);for(intele:res){System.out.print(ele+" ");}}}
Python
defspirallyTraverse(mat):m,n=len(mat),len(mat[0])res=[]# Initialize boundariestop,bottom,left,right=0,m-1,0,n-1# Iterate until all elements are printedwhiletop<=bottomandleft<=right:# Print top row from left to rightforiinrange(left,right+1):res.append(mat[top][i])top+=1# Print right column from top to bottomforiinrange(top,bottom+1):res.append(mat[i][right])right-=1# Print bottom row from right to left (if exists)iftop<=bottom:foriinrange(right,left-1,-1):res.append(mat[bottom][i])bottom-=1# Print left column from bottom to top (if exists)ifleft<=right:foriinrange(bottom,top-1,-1):res.append(mat[i][left])left+=1returnresif__name__=="__main__":mat=[[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]res=spirallyTraverse(mat)print(" ".join(map(str,res)))
C#
usingSystem;usingSystem.Collections.Generic;classGfG{staticList<int>spirallyTraverse(int[,]mat){intm=mat.GetLength(0);intn=mat.GetLength(1);List<int>res=newList<int>();// Initialize boundariesinttop=0,bottom=m-1,left=0,right=n-1;// Iterate until all elements are printedwhile(top<=bottom&&left<=right){// Print top row from left to rightfor(inti=left;i<=right;++i){res.Add(mat[top,i]);}top++;// Print right column from top to bottomfor(inti=top;i<=bottom;++i){res.Add(mat[i,right]);}right--;// Print bottom row from right to left (if exists)if(top<=bottom){for(inti=right;i>=left;--i){res.Add(mat[bottom,i]);}bottom--;}// Print left column from bottom to top (if exists)if(left<=right){for(inti=bottom;i>=top;--i){res.Add(mat[i,left]);}left++;}}returnres;}staticvoidMain(string[]args){int[,]mat={{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};List<int>res=spirallyTraverse(mat);Console.WriteLine(string.Join(" ",res));}}
JavaScript
functionspirallyTraverse(mat){constm=mat.length;constn=mat[0].length;constres=[];// Initialize boundarieslettop=0,bottom=m-1,left=0,right=n-1;// Iterate until all elements are printedwhile(top<=bottom&&left<=right){// Print top row from left to rightfor(leti=left;i<=right;++i){res.push(mat[top][i]);}top++;// Print right column from top to bottomfor(leti=top;i<=bottom;++i){res.push(mat[i][right]);}right--;// Print bottom row from right to left (if exists)if(top<=bottom){for(leti=right;i>=left;--i){res.push(mat[bottom][i]);}bottom--;}// Print left column from bottom to top (if exists)if(left<=right){for(leti=bottom;i>=top;--i){res.push(mat[i][left]);}left++;}}returnres;}// Driver Codeconstmat=[[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]];constres=spirallyTraverse(mat);console.log(res.join(" "));