题目描述
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵: 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.
/*
思想,用左上和右下的坐标定位出一次要旋转打印的数据,一次旋转打印结束后,往对角分别前进和后退一个单位。
提交代码时,主要的问题出在没有控制好后两个for循环,需要加入条件判断,防止出现单行或者单列的情况。
*/
#include<iostream>
#include<vector>
using namespace std;
class Solution
{
public:
vector<int> printMatrix(vector<vector<int>> matrix)
{
int row=matrix.size();
int col=matrix[0].size();
vector<int> res;
//输入的二维数组非法 返回空的数组
if(row==0 ||col ==0) return res;
//定义四个关键变量,表示左上和右下的打印范围
int left=0,top=0,right=col-1,bottom=row-1;
while(left<=right&&top<=bottom)
{
//从左到右
for(int i=left;i<=right;++i)
{
res.push_back(matrix[top][i]);
}
//从上到下
for(int i=top+1;i<=bottom;++i)
{
res.push_back(matrix[i][right]);
}
//从右到左
if(top!=bottom)
{
for(int i=right-1;i>=left;--i)
res.push_back(matrix[bottom][i]);
}
//从下到上
if(left!=right)
{
for(int i=bottom-1;i>top;--i)
res.push_back(matrix[i][left]);
}
left++;top++;right--;bottom--;
}
return res;
}
};
//以下为测试代码
int main()
{
Solution sol;
vector<vector<int> >test={
{1,2,3,4,5},
{6,7,8,9,10},
{11,12,13,14,15},
{16,17,18,19,20}
};
//打印矩阵
for(unsigned int k=0;k<test.size();k++)
{
for(unsigned int i=0;i<test[0].size();i++)
{
cout<<" "<<test[k][i];
}
cout<<endl;
}
//调用方法
vector<int> ct=sol.printMatrix(test);
for(unsigned int k=0;k<ct.size();k++)
{
cout<<" "<<ct[k];
}
return 0;
}
腾讯2016春 后台开发实习生 笔试编程题
蛇形矩阵:作为一种常用的数学数列,是由1开始的自然数一次排列成的一个N*N的正方形矩阵,数字依次由外而内的递增,如下面的实例:
n=3的蛇形矩阵:
1 2 3
8 9 4
7 6 5
n=6的蛇形矩阵:
1 2 3 4 5 6
20 21 22 23 24 7
19 32 33 34 25 8
18 31 36 35 26 9
17 30 29 28 27 10
16 15 14 13 12 11
此题要求输入蛇形矩阵宽度N,输出整个蛇形矩阵结果,注意输出格式要求按照矩阵
从上至下的依次按行输出,每行中间无需换行输出。
样本输入:3
样本输出:1 2 3 8 9 4 7 6 5
AC代码:
/*
形成N*N的正方形矩阵
数字依次由外而内的递增
n=3
1 2 3
8 9 4
7 6 5
思路:依然定义left=0,top=0,right=col-1,bottom=row-1
*/
#include<cstdio>
#include<iostream>
#include<vector>
using namespace std;
class Solution
{
public:
void CreateJuzheng(int x)
{
vector<vector<int>> res;
res.resize(x, vector<int>(x));//分配空间
//不分配空间的话 不使用 push_back
//无法使用这个容器 比如用=号的方式
//因为元素没有被分配
//int res[100][100];
//x为需要形成的矩阵阶数
//那么矩阵的长是X 宽也是X
if(x<=0)
return ;
//左上,右下
int left=0,top=0,right=x-1,bottom=x-1;
int m=0;//m为全局变量
while(left<=right&&top<=bottom)
{
//从左至右
for(int i=left;i<=right;++i)
res[left][i]=++m;
//从上到下
for(int i=top+1;i<=bottom;++i)
res[i][right]=++m;
//从右到左
if(top!=bottom)
{
for(int i=right-1;i>=left;--i)
{
res[bottom][i]=++m;
}
}
//从下到上
if(left!=right)
{
for(int i=bottom-1;i>top;--i)
{
res[i][left]=++m;
}
}
left++;top++;right--;bottom--;
}
for(int i=0;i<x;i++)
{
for(int j=0;j<x;j++)
{
cout<<res[i][j]<<" ";
}
// cout<<endl;
}
}
};
int main()
{
int x;
cin>>x;
Solution sol;
sol.CreateJuzheng(x);
}