新浪和轻芒面试都遇到一道简单的算法题。不会做的话真是太丢人了。
一边听音乐,一边把代码撸出来了。听歌有时可以使注意力集中哦,而且会感觉放松,面试有时紧张,简单的问题都会容易错。
问题:给出一个 m*n 的矩阵,顺时针打印这个矩阵。例如这是一个 3行x3列的矩阵:
1 2 3
5 5 6
4 5 7
打印的结果就是:1,2,3,6,7,5,4,5,5,6
思路:正常思路就是按顺序遍历,关键是做好边界处理,定好循环条件。
- 一次遍历一行或一列,遍历到头。
- 记录当前遍历到哪一行哪一列了
- 记录当前还剩多少行,多少列没有遍历,依据这个来决定要不要继续循环
- 记录当前的遍历的起始点。比如例子中遍历的顺序是:
-
0-2
列 : 1,2,3 -
1-2
行 : 6,7 -
1-0
列 : 5,4 -
1-1
行 : 5 -
1-2
列 : 5,6
按照这个规律来写代码, 虽然变量有点多,不过我觉得这样思路很清晰。
public static List<Integer> print(int[][] matrix) {
List<Integer> results = new ArrayList<>();
// 读完后剩余的行数
int remainingRows = matrix.length;
// 读完后剩余的列数
int remainingColumns = matrix[0].length;
// 标记当前应从第几列开始读
int startColumn = 0;
// 标记当前应读到哪一列结束
int endColumn;
// 标记当前应从第几行开始读
int startRow;
// 标记当前应读到哪一行结束
int endRow;
// 标记当前的读到了第几列
int curColumns = 0;
// 标记当前的读到了第几行
int curRows = 0;
// 循环条件:当还有剩余的 列/行 没遍历
while (remainingColumns > 0 || remainingRows > 0) {
// 顺时针开始循环
// 1.从左到右打印第一行
if (remainingRows <= 0) return results;
if (startColumn > 0) {
startColumn = curColumns + 1;
} else {
startColumn = 0;
}
endColumn = startColumn + remainingColumns - 1;
System.out.println("从" + startColumn + "列-" + endColumn + "列开始遍历");
for (int i = startColumn; i <= endColumn; i++) {
curColumns = i;
results.add(matrix[curRows][i]);
}
// 读完一行-1
remainingRows--;
System.out.println("还剩" + remainingRows + "行,当前是第" + curColumns + "列");
// 2.从上到下
if (remainingColumns <= 0) return results;
startRow = curRows + 1;
endRow = startRow + remainingRows - 1;
System.out.println("从" + startRow + "行-" + endRow + "行开始遍历");
for (int i = startRow; i <= endRow; i++) {
curRows = i;
results.add(matrix[i][curColumns]);
}
remainingColumns--;
System.out.println("还剩" + remainingColumns + "列");
// 3. 从右到左
if (remainingRows <= 0) return results;
startColumn = curColumns - 1;
endColumn = startColumn - remainingColumns + 1;
System.out.println("从" + startColumn + "列-" + endColumn + "列开始遍历");
for (int i = startColumn; i >= endColumn; i--) {
curColumns = i;
results.add(matrix[curRows][i]);
}
remainingRows--;
System.out.println("还剩" + remainingRows + "行,当前是第" + curColumns + "列");
// 4. 从下到上
if (remainingColumns <= 0) return results;
startRow = curRows - 1;
endRow = startRow - remainingRows + 1;
System.out.println("从" + startRow + "行-" + endRow + "行开始遍历");
for (int i = startRow; i >= endRow; i--) {
curRows = i;
results.add(matrix[i][curColumns]);
}
remainingColumns--;
System.out.println("还剩" + remainingColumns + "列");
}
return results;
}
网友评论