Skip to content

Bug issues in Spiral Matrix Code | L4 2D Arrays #19

@TharunBalaji2004

Description

@TharunBalaji2004

I used the Spiral Matrix code for solving Leetcode problem, it seems like some of the testcases are not getting passed. I changed the code little bit, by replacing the increment/decrement variables and conditional statement for printing Bottom and Right Boundaries.
Checkout this:

public List<Integer> spiralOrder(int[][] matrix) {
    int startRow = 0;
    int startCol = 0;
    int endRow = matrix.length-1;
    int endCol = matrix[0].length-1;
    List<Integer> list = new ArrayList<Integer>();

    while(startCol <= endRow && startRow <= endCol){
        for(int i=startRow; i<=endCol; i++)
           list.add(matrix[startCol][i]);
        startCol++;

        for(int i=startCol; i<=endRow; i++)
            list.add(matrix[i][endCol]);
        endCol--;

        if (startCol <= endRow){
            for(int i=endCol; i>=startRow; i--)
                list.add(matrix[endRow][i]);
            endRow--;
        }

        if (startRow <= endCol){
            for(int i=endRow; i>=startCol; i--)
                list.add(matrix[i][startRow]);
            startRow++;
        }
    }

    return list;
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions