# AC intuitive solution with explanation

• ``````public class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> res= new ArrayList<Integer>();
if(matrix.length==0) return res;
int m=matrix.length,n=matrix[0].length;
boolean[][] table = new boolean[m][n];
int i=0,j=0;
table[i][j]=true;
boolean up=false,down=false, right=false,left=false;
while(!up||!down||!right||!left){
// at this point check if it can go right, if it can, go all the way to the right most
right=j+1<n? table[i][j+1]:true;
while(!right){
table[i][j]=true;
right=j+1<n? table[i][j+1]:true;
}
// time to go down
down=i+1<m? table[i+1][j]:true;
while(!down){
table[i][j]=true;
down=i+1<m? table[i+1][j]:true;
}
// time to go left
left=j-1>=0? table[i][j-1]:true;
while(!left){
table[i][j]=true;
left=j-1>=0? table[i][j-1]:true;
}
// time to go up
up=i-1>=0 ? table[i-1][j]:true;
while(!up){
table[i][j]=true;
up=i-1>=0 ? table[i-1][j]:true;

}
// check if there is one way to go, if not return;
up=i-1>=0 ? table[i-1][j]:true;
down=i+1<m? table[i+1][j]:true;
right=j+1<n? table[i][j+1]:true;
left=j-1>=0? table[i][j-1]:true;
}
return res;

}
``````

}

• Any suggestions for improvement are welcome

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.