Wednesday, 13 May 2015

Matrix Parsing - Spiral Way

Problem Statement:

Input:

1    2    3    4
5    6    7    8
9    10  11  12
13  14  15  16

Output:


1, 2, 3, 4, 8, 12, 16, 15, 14, 13, 9, 5, 6, 7, 11, 10

Solution in Java:

public class MatrixSpiralParser {

    public static void main(String[] args) {
        int[][] matrix = new int[][]{ {1,2,3,4}, {5,6,7,8}, {9, 10, 11, 12}, {13,14,15,16}};
        parseSprialWay(matrix);
    }
    
    private static void parseSprialWay(int[][] matrix) {
        int startRow = 0;
        int endRow = matrix.length - 1;
        int startColumn = 0;
        int endColumn = matrix[endRow-1].length -1;
        
        while(startRow <= endRow && startColumn <= endColumn) {
            
            for(int i = startColumn ; i <= endColumn ; i++) {
                System.out.print(matrix[startRow][i] + ", ");
            }
            startRow++;
            
            for(int i= startRow; i<= endRow; i++) {
                System.out.print(matrix[i][endColumn] + ", ");
            }
            endColumn--;
            
            for(int i = endColumn; i >= startColumn ; i--) {
                System.out.print(matrix[endRow][i] + ", ");
            }
            endRow--;
            
            for(int i= endRow; i >= startRow ; i-- ) {
                System.out.print(matrix[i][startColumn] + ", ");
            }
            startColumn++;
        }
        
    }

}

No comments:

Post a Comment