Prompt
Write a function that takes in an n x m twodimensional array (that can be square-shaped when n === m) and returns a one-dimensionalarray of all the array’s elements in spiralorder.
Spiral order starts at the top left corner of thetwo-dimensional array, goes to the right, and proceeds in a spiral pattern all the way until every element has been visited.
Sample Input
array = [
[1, 2, 3, 4],
[12, 13, 14, 5],
[11, 16, 15, 6],
[10, 9, 8, 7],
]
Sample Output
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10,11,12,13,14,15, 16]
Solution 1
import java.util.*;
class Program {
// O(n) time| O(n) space
public static List<Integer> spiralTraverse(int[][] array) {
// Write your code here.
var result = new ArrayList<Integer>();
var startRow = 0;
var endRow = array.length - 1;
var startCol = 0;
var endCol = array[0].length - 1;
while (startRow <= endRow && startCol <= endCol) {
for (int col = startCol; col <= endCol; col++) {
result.add(array[startRow][col]);
}
for (int row = startRow + 1; row <= endRow ; row++ ) {
result.add(array[row][endCol]);
}
for (int col = endCol - 1; col >= startCol; col--) {
if (startRow == endRow) break; //A
result.add(array[endRow][col]);
}
for (int row = endRow - 1 ; row > startRow ; row-- ) {//B
if (startCol == endCol) break;
result.add(array[row][startCol]);
}
startRow += 1;
endRow -= 1;
startCol += 1;
endCol -= 1;
}
return result;
}
}
# 1 A
画图的时候,多考虑情况,把能想到的数据类型都列出来,一个个处理
# 1B
每次在做重复性工作的时候,一定要考虑特殊情况,比如这里是> 而不是>=
Solution 2
import java.util.*;
class Program {
public static List<Integer> spiralTraverse(int[][] array) {
var result = new ArrayList<Integer>();
spiralTraverseHelper(array, 0, array.length - 1, 0, array[0].length - 1, result);
return result;
}
public static void spiralTraverseHelper(
int[][] array,
int startRow,
int endRow,
int startCol,
int endCol,
ArrayList<Integer> result) {
if (startRow > endRow || startCol > endCol) {
return;
}
for (int col = startCol; col <= endCol; col++) {
result.add(array[startRow][col]);
}
for (int row = startRow + 1; row <= endRow ; row++ ) {
result.add(array[row][endCol]);
}
for (int col = endCol - 1; col >= startCol; col--) {
if (startRow == endRow) break; //A
result.add(array[endRow][col]);
}
for (int row = endRow - 1 ; row > startRow ; row-- ) {//B
if (startCol == endCol) break;
result.add(array[row][startCol]);
}
spiralTraverseHelper(array, startRow + 1, endRow - 1, startCol + 1, endCol - 1, result);
}
}
How to Bug Free
仔细画图,列出所有的情况,每个情况处理后划掉
画图画完,每次画图到“最后一步“,认真考虑
Why can’t I Solve this
其实想到了这样解决问题,但是当时觉得这样做会比较“笨”,所以直接排除了(题目做的太少了
Conclusion
仔细画图