Skip to content

Conversation

@jhm9595
Copy link
Owner

@jhm9595 jhm9595 commented Sep 9, 2022

Time Complexity : O(N)

break;
}
}

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(1) Add a class "Direction".

class Direction {
    private int r; // Each step for row-direction
    private int c; // Each step for column-direction
    public int getR() {
        return r;
    }
    public int getC() {
        return c;
    }
}

You can initialize a static array of Direction with values

(0, 1)
(1, 0)
(0, -1)
(-1, 0)

(2) Add a util function outOfBound(int[][] matrix, int r, int c)

private boolean outOfBound(int[][] matrix, int r, int c) {
    return r >= 0 && c >= 0 && r < matrix.length && c < matrix[0].length;
}

If you have (1) and (2), the implementation in your while loop can be simplified into:

int nextR = r + directions[currentDirection].getR();
int nextC = c + directions[currentDirection].getC();

if(outOfBound(matrix, nextR, nextC) || traceMap[nextR][nextC] == 1) {
    currentDirection = (currentDirection + 1) % 4;
} else {
    r = nextR;
    c = nextC;
    result.add(matrix[r][c]);
    traceMap[r][c] = 1;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants