题目描述
牛客网:JZ19 顺时针打印矩阵
给定矩阵,从左上角开始以回形针方向遍历数组,返回遍历结果。如下图所示
示例:
输入:
[
[ 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]
题目解析
返回的结果可以用数组表示,因为数组的大小是已知的,也可以用列表来存储遍历结果。本文为了方便使用列表作为返回值。
遍历时需要考虑遍历方向和是否遍历结束。
- 遍历方向的顺序是一致的,可以依次对每个方向进行遍历
- 判断遍历终止条件。由于遍历从矩阵最外圈开始不断向里,可以通过边界线来判断是否结束遍历。
public List<Integer> beans(int[][] matrix){
List<Integer> ans = new ArrayList<Integer>();
int m = matrix.length;
int n = matrix[0].length;
if(m <= 0 || n <= 0){
return ans;
}
int m_curPos = 0;
int n_curPos = 0;
while(m_curPos < m && n_curPos < n){
// 向右走
for(int j = n_curPos;j < n && m_curPos < m;j++){
ans.add(matrix[m_curPos][j]);
}
m_curPos++;
// 向下走
for(int i = m_curPos;i < m && n_curPos < n ;i++){
ans.add(matrix[i][n - 1]);
}
n--;
// 向左走
for(int j = n - 1;j >= n_curPos && m_curPos < m;j--){
ans.add(matrix[m - 1][j]);
}
m--;
// 向上走
for(int i = m - 1;i >= m_curPos && n_curPos < n;i--){
ans.add(matrix[i][n_curPos]);
}
n_curPos++;
}
return ans;
}
- 时间复杂度:O(m * n),遍历整个数组元素