我的想法就是先定下四个角的坐标,然后按行和列打印
这里很重要的是,如果你想用x,y来代表坐标,一点不要把数组的规律和坐标系搞混淆了,这样可能你打印出来是反的.
这里我是这样做的:
数组的下标是:
a00 a01 a02...
a10 a11 a12..
a20 a21 a22...
所以我使用x代表第一个下标,y代表第二个下标
a[x][y]
形象的:
大家可以根据这个图:
- 确定四个角的"坐标"
- 确定打印的顺序
这是驱动函数:
//judge if input legall!!!
void print_left_right(int a[][100], int start, int end,int y);//x goes up
void print_right_left(int a[][100], int start, int end,int y);//x goes down
void print_up_down(int a[][100], int start, int end,int x);
void print_down_up(int a[][100], int start, int end,int x);
//print an matrix by circle
//the matrix is m*n
void print_matrix(int a[][100], int m, int n)
{
int startX, startY,endX,endY;
startX = 0;
startY = 0;
endX = m - 1;
endY = n - 1;
while (startX < endX && startY<endY)
{
print_left_right(a, startY, endY,startX);
print_up_down(a, startX + 1, endX, endY);
print_right_left(a, endY - 1, startY, endX);
print_down_up(a, endX - 1, startX + 1, startY);
startX++;
endX--;
startY++;
endY--;
}//when breaks,one line remains
if (endX == startX&&endY != startY)
{
//std::cout << "print between x=" << endX << " y=" << startY << " & " << endY;
print_left_right(a, startY, endY, startX);
}
else if (endX != startX&&endY == startY)
{
//std::cout << "print between x=" << endX << " y=" << startY << " & " << endY;
print_up_down(a, startX, endX, startY);
}
else if (startX == endX&&startY == endY)
std::cout << a[startX][startY];
}
- 每打印一圈,坐标就往里面缩小一圈
- 判断临界值;
- 处理行和列相同和不相同的情况
- 四个打印函数要判断输入的参数是否合法
接着写具体的函数:
void print_left_right(int a[][100], int start, int end, int x)//y goes up
{
if ( start > end)
return;
for (int i = start; i <= end; i++)
{
std::cout << a[x][i] << " ";
}
}
void print_right_left(int a[][100], int start, int end, int x)//x goes down
{
if (start < end)
return;
for (int i = start; i >= end; i--)
{
std::cout << a[x][i] << " ";
}
}
void print_up_down(int a[][100], int start, int end, int y)
{
if ( start > end)
return;
for (int i = start; i <= end; i++)
{
std::cout << a[i][y] << " ";
}
}
void print_down_up(int a[][100], int start, int end, int y)
{
if (start < end)
return;
for (int i = start; i >= end; i--)
{
std::cout << a[i][y] << " ";
}
}
void getMatrix(int a[][100],int m,int n)
{
std::cout << "please input a matrix:" << "\n";
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
std::cin >> a[i][j];
}
}
int main()
{
int a[100][100];
int m, n;
std::cout << "please input number of hang:" << "\n";
std::cin >> m;
std::cout << "please input number of lie:" << "\n";
std::cin >> n;
//
getMatrix(a,m, n);
print_matrix(a, m, n);
}
其实写这个的时候我出了好多错误,都是泪啊
比如手抖写错了,一直没改,潜伏到最后才发现:
while (startX <= endX || startY >= startY)
尼玛第二个判断也是醉了
还有一点就是while的出口条件,我这样写可以,但是也可以是其他的,大家自己在纸上写写画画就清楚了