返回
算法题:顺时针打印矩阵,理清思路,轻松解题!
前端
2023-10-27 07:58:44
问题
给定一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
例如,对于以下矩阵:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
顺时针打印结果为:
1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10
算法步骤
该算法的步骤如下:
- 初始化四个变量:top、bottom、left和right,分别表示矩阵的上边界、下边界、左边界和右边界。
- 按照从上到下、从左到右的顺序遍历矩阵,将每个元素添加到结果列表中。
- 更新top、bottom、left和right变量,缩小矩阵的范围。
- 重复步骤2和步骤3,直到遍历完整个矩阵。
算法实现
该算法的Java代码实现如下:
public class ClockwisePrintMatrix {
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16}
};
System.out.println(clockwisePrintMatrix(matrix));
}
public static List<Integer> clockwisePrintMatrix(int[][] matrix) {
List<Integer> result = new ArrayList<>();
int top = 0, bottom = matrix.length - 1, left = 0, right = matrix[0].length - 1;
while (top <= bottom && left <= right) {
// 从左到右遍历矩阵的上边界
for (int i = left; i <= right; i++) {
result.add(matrix[top][i]);
}
// 从上到下遍历矩阵的右边界
for (int i = top + 1; i <= bottom - 1; i++) {
result.add(matrix[i][right]);
}
// 从右到左遍历矩阵的下边界
if (top < bottom) {
for (int i = right; i >= left; i--) {
result.add(matrix[bottom][i]);
}
}
// 从下到上遍历矩阵的左边界
if (left < right) {
for (int i = bottom - 1; i > top; i--) {
result.add(matrix[i][left]);
}
}
top++;
bottom--;
left++;
right--;
}
return result;
}
}
时间复杂度
该算法的时间复杂度为O(m*n),其中m和n分别是矩阵的行数和列数。
空间复杂度
该算法的空间复杂度为O(1),因为该算法不需要额外的空间来存储中间结果。
结论
该算法能够有效地解决顺时针打印矩阵的问题。该算法易于理解和实现,具有较好的时间复杂度和空间复杂度。