SpiralMatrix

public class SpiralMatrix {

    public static void main(String[] args) {
        int arr[][] = {
                {1, 2, 3, 4},                {5, 6, 7, 8},                {9, 10, 11, 12},                {13, 14, 15, 16},                {17, 18, 19, 20}
                };        for(int x[]: arr){
            for(int y: x){
                System.out.print(y+ " ");            }
            System.out.println();        }
        int len = arr.length;        int top = 0;        int down = len-1;        int left = 0;        int right = arr[0].length-1;        int direction = 0;        while(top<=down && left<=right){
            if(direction == 0){
                for(int i=left; i<=right; i++){
                    System.out.print(arr[top][i] + ",");                }
                top += 1;            }else if(direction == 1){
                for(int i=top; i<=down; i++){
                    System.out.print(arr[i][right]+ ",");                }
                right -= 1;            }else if(direction == 2){
                for(int i=right; i>=left;i--){
                    System.out.print(arr[down][i]+ ",");                }
                down -= 1;            }else if(direction == 3){
                for(int i=down; i>=top; i--){
                    System.out.print(arr[i][left]+ ",");                }
                left += 1;            }



            direction = (direction+1) %4;        }

    }
}

Comments