蛇形矩阵
输入两个整数 n和 m,输出一个 n行 m 列的矩阵,将数字 1 到 n×m 按照回字蛇形填充至矩阵中。
具体矩阵形式可参考样例。
输入格式
输入共一行,包含两个整数 n 和 m。
输出格式
输出满足要求的矩阵。
矩阵占 n 行,每行包含 m 个空格隔开的整数。
数据范围
1≤n,m≤100
输入样例:
3 3
输出样例:
1 2 3
8 9 4
7 6 5
好家伙,纯模拟,耐心就可以,纯耗时间,没有技巧…..
贴个代码:
#include
using namespace std ;
const int N = 1010 ;
int f[N][N] ;
int main()
{
int n , m ;
cin >> n >> m ;
int all = n*m ;
int cnt = 0 ;
int top1 =n , top2 = m , bottom1 = 1 , bottom2 = 1 ;
while(all > 0 )
{
for(int j = bottom2 ; j <= top2 ; j++)
{
f[bottom1][j] = ++cnt ;
all -- ;
}
top2 -- ;
for(int i = bottom1 ; i <= top1 ; ++i)
{
f[i][top2+1] = ++cnt ;
all -- ;
}
top1 -- ;
for(int j = top2 ; j >= bottom2 ; --j)
{
f[top1+1][j] = ++cnt ;
all -- ;
}
bottom2 ++ ;
for(int i = top1 ; i <= bottom1 ; --i)
{
f[i][bottom2] = ++cnt ;
all -- ;
}
bottom1 ++ ;
}
for(int i = 1 ; i <= n ; ++i)
{
for(int j = 1 ; j <= m ;++j)
{
cout << f[i][j] << " " ;
}
cout << endl ;
}
return 0 ;
}
注意对称美还有一些细节就行了……. 模拟的题目是最无聊的…….