Z形打印二位数组:
思路:
打印斜线。
注意更换方向的条件。
代码:
#include<iostream>
#include<vector>
using namespace std;
void print(vector<vector<int> > matrix)
{
//r:行号, m:行数
int r=0,m=matrix.size();
//c:列号,n:列数
int c=0,n=matrix.front().size();
//l2r:从左到右,
bool l2r=true;
while(r<m&&c<n)
{
//从左下到右上的斜线
if(l2r)
{
cout<<matrix[r][c]<<" ";
//现在在第一行,列未到边界,这时只能向右走
if(r==0&&c<(n-1))
{
l2r=!l2r;//方向切换
c++;
continue;
}
else if(r>=0&&c==n-1)
{ //现在是在最后一列,只能向下走
l2r=!l2r;
r++;
continue;
}
else
{ //继续走上坡
r--;
c++;
}
}
else
{ //反,走下坡
cout<<matrix[r][c]<<" ";
if(c==0&&r<(m-1))
{ //走到第一列,只能往下走
l2r=!l2r;
r++;
continue;
}
else if(r==m-1)
{ //到最后一行,只能往右走
l2r=!l2r;
c++;
continue;
}
else
{
r++;
c--;
}
}
}
}
int main()
{
vector<vector<int> > arr;
int row=3,col=4;
//二维向量赋初值
for(int i=0,k=1;i<row;i++)
{
vector<int> temp;
for(int j=0;j<col;j++)
{
temp.push_back(k);
k++;
}
arr.push_back(temp);
}
//打印二维向量
for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++)
{
cout<<arr[i][j]<<" ";
}
cout<<endl;
}
cout<<endl;
print(arr);
return 0;
}