Skip to content

Conversation

02-Shivaraj
Copy link

No description provided.

int count = 0;
int row = 0;
int col = 0;
boolean right = true;

Choose a reason for hiding this comment

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

Too many boolean flags for directions

  • right, left, up, down, and curr lead to bloated logic and repetitive conditionals.
  • This could be replaced by a direction array and an index to keep it clean.

Choose a reason for hiding this comment

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

`public List spiralOrder(int[][] matrix) {
List result = new ArrayList<>();
if (matrix == null || matrix.length == 0) return result;

 int top = 0; int bottom = matrix.length - 1; int left = 0; int right = matrix[0].length - 1; while (top <= bottom && left <= right) { // move right for (int i = left; i <= right; i++) { result.add(matrix[top][i]); } top++; // move down for (int i = top; i <= bottom; i++) { result.add(matrix[i][right]); } right--; // move left if (top <= bottom) { for (int i = right; i >= left; i--) { result.add(matrix[bottom][i]); } bottom--; } // move up if (left <= right) { for (int i = bottom; i >= top; i--) { result.add(matrix[i][left]); } left++; } } return result; } 

}`

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

Labels

None yet

2 participants