implement spiralTraversal method in MainExercises
This commit is contained in:
@@ -23,41 +23,39 @@ public class MainExercises
|
|||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
/*
|
|
||||||
SPIRAL TRAVERSAL OF A RECTANGULAR MATRIX
|
|
||||||
|
|
||||||
Given a rectangular matrix (2D array) of integers, this method traverses
|
|
||||||
it in a spiral order (clockwise from outside to inside) and returns
|
|
||||||
the elements as a 1D array.
|
|
||||||
|
|
||||||
EXAMPLE:
|
|
||||||
Input matrix:
|
|
||||||
1 2 3
|
|
||||||
4 5 6
|
|
||||||
7 8 9
|
|
||||||
|
|
||||||
Spiral order: start at top-left (1), go right →, then down ↓,
|
|
||||||
then left ←, then up ↑, then repeat inward.
|
|
||||||
|
|
||||||
Result: {1, 2, 3, 6, 9, 8, 7, 4, 5}
|
|
||||||
|
|
||||||
so you should walk in that matrix in a curl and then add the numbers in order you've seen them in a 1D array
|
|
||||||
|
|
||||||
RECTANGULAR MATRIX ASSUMPTION:
|
|
||||||
This method assumes the input matrix is RECTANGULAR (all rows have
|
|
||||||
the same number of columns). In Java, we can verify this because
|
|
||||||
2D arrays might be jagged (rows of different lengths).
|
|
||||||
|
|
||||||
IMPORTANT: In Java, we do NOT need to pass rows and cols!
|
|
||||||
The 2D array 'matrix' knows its own dimensions:
|
|
||||||
- Number of rows: matrix.length
|
|
||||||
- Number of columns: matrix[0].length (if rectangular)
|
|
||||||
*/
|
|
||||||
public int[] spiralTraversal(int[][] matrix) {
|
public int[] spiralTraversal(int[][] matrix) {
|
||||||
// todo
|
int rows = matrix.length, cols = matrix[0].length;
|
||||||
return null;
|
int elementCount = rows * cols, curElement = 0;
|
||||||
|
int[] result = new int[elementCount];
|
||||||
|
|
||||||
|
for (int leyer = 0; curElement < elementCount; leyer++) {
|
||||||
|
int curi = leyer, maxi = rows - 1 - leyer;
|
||||||
|
int curj = leyer, maxj = cols - 1 - leyer;
|
||||||
|
|
||||||
|
for (;curj < maxj && curElement < elementCount; curj++, curElement++)
|
||||||
|
{
|
||||||
|
result[curElement] = matrix[curi][curj];
|
||||||
|
}
|
||||||
|
for (;curi < maxi && curElement < elementCount; curi++, curElement++)
|
||||||
|
{
|
||||||
|
result[curElement] = matrix[curi][curj];
|
||||||
|
}
|
||||||
|
for (;curj > leyer && curElement < elementCount; curj--, curElement++)
|
||||||
|
{
|
||||||
|
result[curElement] = matrix[curi][curj];
|
||||||
|
}
|
||||||
|
for (;curi > leyer && curElement < elementCount; curi--, curElement++)
|
||||||
|
{
|
||||||
|
result[curElement] = matrix[curi][curj];
|
||||||
|
}
|
||||||
|
|
||||||
|
if (curi == maxi || curj == maxj) {
|
||||||
|
if (curi == maxi && curj == maxj) result[curElement] = matrix[curi][curj];
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
|
|||||||
Reference in New Issue
Block a user