题目描述
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下 4 × 4 4 \times 4 4×4矩阵: 12345678910111213141516 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 12345678910111213141516 则依次打印出数字 1 , 2 , 3 , 4 , 8 , 12 , 16 , 15 , 14 , 13 , 9 , 5 , 6 , 7 , 11 , 10 1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10 1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.
解题思路
画图找好循环中的截止条件,数组下标的范围即可,方法有很多种。
代码实现
class Solution {
public:
vector<int> printMatrix(vector<vector<int> > matrix)
{
if (matrix.empty())
return{}; // 不能写成 return 0;
vector<int> v;
int row = 0, col = 0;
int i = 0;
int sum = matrix.size() * matrix[0].size(); // 求二维数组元素的个数
cout << "sum = " << sum << endl;
int count = 0;
while (i < matrix.size())
{
for (col = i; col < matrix[row].size() - i; col++)
{
v.push_back(matrix[row][col]);
count++;
if (count == sum)
break;
}
if (count == sum)
break;
col--;
for (row = i + 1; row < matrix.size() - i; row++)
{
v.push_back(matrix[row][col]);
count++;
if (count == sum)
break;
}
if (count == sum)
break;
row--;
for (col = matrix[row].size() - i - 2; col >= i; col--)
{
v.push_back(matrix[row][col]);
count++;
if (count == sum)
break;
}
if (count == sum)
break;
col++;
for (row = matrix.size() - i - 2; row > i; row--)
{
v.push_back(matrix[row][col]);
count++;
if (count == sum)
break;
}
if (count == sum)
break;
row++;
i++;
}
return v;
}
};
关于vector的扩展知识
1、若vector类型的函数返回为空,不能写成 return 0;
if (matrix.empty())
return {}; // 不能写成 return 0;
2、如何初始化二维动态数组
vector<vector<int>> v(4);// 定义一个row = 4的二维数组
int i = 0, k = 0, j = 1;
for (i = 0; i < 4; i++)
{
for (k = 0; k < 4; k++)
{
v[i].push_back(j++);
}
}
3、如何遍历动态二维数组
vector<vector<int>>::iterator it1; //定义二维数组迭代器
vector<int>::iterator it2; // 定义一维数组迭代器
for (it1 = v.begin(); it1 != v.end(); it1++)
{
for (it2 = it1->begin(); it2 != it1->end(); it2++)
{
cout << *it2 << " ";
}
cout << endl;
}