問題描述
回形取數就是沿矩陣的邊取數,若目前方向上無數可取或已經取過,則左轉90度。一開始位于矩陣左上角,方向向下。
輸入格式
輸入第一行是兩個不超過200的正整數m, n,表示矩陣的行和列。接下來m行每行n個整數,表示這個矩陣。
輸出格式
輸出隻有一行,共mn個數,為輸入矩陣回形取數得到的結果。數之間用一個空格分隔,行末不要有多餘的空格。
樣例輸入
3 3
1 2 3
4 5 6
7 8 9
樣例輸出
1 4 7 8 9 6 3 2 5
3 2
1 2
3 4
5 6
1 3 5 6 4 2
此題的核心是控制
假設i 控制豎坐标 j控制橫坐标,
那麼此題的思路就是先控制i變化,j不變,然後j變化,i不變化,如此往複,結束條件是啥,因為要取到所有的數字,是以一共要取m*n次,,這就是結束條件。
對于代碼中為啥要引入 -1 這個判斷條件,其本質是因為x–之類的會找到上次的位置,導緻沒有找完,比如題中給出的執行個體1 ,如果沒有此判斷條件,會在找一次1,(1 4 7 8 9 6 3 2 1)滿足了m*n這個條件,程式提前退出,沒有找到5。
#include <cstdio>
#include <vector>
#include <cstring>
#include <iostream>
using namespace std;
int main()
{
int m, n;
int i, j, num = 0;
int a[205][205];
memset(a, -1, sizeof(a));
scanf("%d%d", &m, &n);
for(i = 0; i < m; i++)
for(j = 0; j < n; j++)
scanf("%d", &a[i][j]);
int tot = 0, x = -1, y = 0;
while(tot < m * n)
{
while(x + 1 < m && a[x + 1][y] != -1)
{
printf("%d ", a[++x][y]);
a[x][y] = -1;
++tot;
}
while(y + 1 < n && a[x][y + 1] != -1)
{
printf("%d ", a[x][++y]);
a[x][y] = -1;
++tot;
}
while(x - 1 >= 0 && a[x - 1][y] != -1)
{
printf("%d ", a[--x][y]);
a[x][y] = -1;
++tot;
}
while(y - 1 >= 0 && a[x][y - 1] != -1)
{
printf("%d ", a[x][--y]);
a[x][y] = -1;
++tot;
}
}
return 0;
}