share my java solution - save the directions(movements)


  • 0
    S

    public static List<Integer> spiralOrder(int[][] matrix) {
    List<Integer> list = new ArrayList<Integer>();
    int[][] dir = new int[][]{{0,1},{1,0},{0,-1},{-1,0}}; //save the directions
    if(matrix == null|| matrix.length == 0 || matrix[0].length == 0){
    return list;
    }
    int i = 0,j = 0,k = 0,top = -1,bottom = matrix.length,right = matrix[0].length,left = -1;
    while(i > top && i < bottom && j < right && j > left){
    //move in one direction
    while(i > top && i < bottom && j < right && j > left){
    list.add(matrix[i][j]);
    i+=dir[k][0];
    j+=dir[k][1];
    }
    //缩减边界,narrow the bound
    switch(k){
    case 0:top++;break;
    case 1:right--;break;
    case 2:bottom--;break;
    case 3:left++;break;
    default:break;
    }
    //回退,backtrace
    i-=dir[k][0];
    j-=dir[k][1];
    //进行下一个方向的移动,next direction
    k = (k+1)%4;
    //避免重复,avoid duplicate elements
    i+=dir[k][0];
    j+=dir[k][1];
    }
    return list;
    }


Log in to reply
 

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