java solution


  • 0
    X

    public class Solution {

    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> res=new ArrayList<Integer>();
        if(matrix==null || matrix.length<1){
            return res;
        }
        int m=matrix.length;
        int n=matrix[0].length;
        boolean[][] flag=new boolean[m][n];
        int i,j;
        for(i=0;i<m;i++){
            for(j=0;j<n;j++){
                flag[i][j]=false;
            }
        }
        i=0;
        j=0;
        while(i<m && j<n && !flag[i][j]){
            while(j<n && !flag[i][j] ){
                res.add(matrix[i][j]);
                flag[i][j]=true;
                j++;
            }
            i++;
            j--;
            while(i<m && !flag[i][j]){
                res.add(matrix[i][j]);
                flag[i][j]=true;
                i++;
            }
            i--;
            j--;
            while(j>=0 && !flag[i][j]){
                res.add(matrix[i][j]);
                flag[i][j]=true;
                j--;
            }
            j++;
            i--;
            while(i>=0 && !flag[i][j]){
                res.add(matrix[i][j]);
                flag[i][j]=true;
                i--;
            }
            i++;
            j++;
        }
        return res;
    }
    

    }


Log in to reply
 

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