Created
January 29, 2018 06:16
-
-
Save KodeSeeker/d452c40c39d87464d0c047f93de31734 to your computer and use it in GitHub Desktop.
SpiralMatrix1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public List<Integer> spiralOrder(List<ArrayList<Integer>> a){ | |
if( a == null || a.isEmpty()) { | |
return null; | |
} | |
// base case 3x3 then tweak | |
int startRow = 0; | |
int startCol = 0; | |
int endRow= a.size(); | |
int endCol = a.get(0).size(); | |
// terminating condition . | |
// if startRow == endRow and startCol == end Col then we print | |
//element a[startRow][Endcol], this is the element in the middle of the array | |
// if only one of the conditions meet then exit because we've covered the whole matrix. | |
while (startRow <=endRow && startCol <= endCol) { | |
//deal with matrices that have an element in the middle/ just one element left. | |
if (startRow == endRow) && (startCol == endCol) { | |
result.add(a.get(startRow).get(startCol)); | |
break; | |
} | |
for (int i= startRow, int j = startCol; j<=endCol-1; j++) { | |
result.add(a.get(i).get(j));//1,2 | |
} | |
for (int i= startRow, int j = endCol; i<=endRow-1; i++) { | |
result.add(a.get(i).get(j));//3,6 | |
} | |
for (int i= endRow, int j = endCol; j>=startCol+1; j--) { | |
result.add(a.get(i).get(j));//9,8 | |
} | |
for (int i= endRow, int j = startCol; i>=startRow+1; i--) { | |
result.add(a.get(i).get(j));//7,4 | |
} | |
startRow++; | |
startCol++; | |
endRow --; | |
endCol --; | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment