写在前面
- 本文含两题,753. 平方矩阵 I、756. 蛇形矩阵
- 切身体会到了 提前预判 相比 悔步,更简单直接
- 在蛇形填数中的体现就是——判断下一步填入的位置是否合理,再移动pos,而不是先移动pos,当出错,再退回来。
题目在这
AC代码(753. 平方矩阵 I)
用了紫书里的蛇形填数源码。然而,啊咧,还是蒟蒻调试了半天O_O
#include <iostream>
#include <cstring>
using namespace std;
const int maxn = 150;
int a[maxn][maxn];
int main()
{
int n;
while (cin >> n && n)
{
memset(a, 0, sizeof(a));
int x = 0, y = 0; //笔的当前坐标
int number = 1;
a[x][y] = number; //第一笔就是 1
int cnt = 1; //填完一个数了
while (cnt < n * n )
{
//用下一笔的位置来判断
//向右, 符合条件,则填入下一笔。 ——提前预判
while (y + 1 < n && !a[x][y + 1])
{
a[x][ ++ y] = number; cnt ++;
}
//向下
while (x + 1 < n && !a[x + 1][y])
{
a[ ++ x][y] = number; cnt ++ ;
}
//向左
while (y - 1 >= 0 && !a[x][y - 1])
{
a[x][-- y] = number; cnt ++ ;
}
//向上
while (x - 1 >= 0 && !a[x - 1][y])
{
a[ -- x][y] = number; cnt ++ ;
}
number ++ ;
}
for (int i = 0; i < n; i ++ )
{
for (int j = 0; j < n; j ++ )
{
cout << a[i][j] << " ";
}
cout << endl;
}
cout << endl;
}
return 0;
}
蛇形填数
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
const int maxn = 150;
int a[maxn][maxn];
int main()
{
int n;
while (cin >> n && n)
{
memset(a, 0, sizeof(a));
int x = 0, y = 0; //初始坐标坐标,(0,0)
int cnt = 1; //初始化第一个数
a[x][y] = cnt;
while (cnt < n * n )
{
//用下一笔的位置来判断
//向右, 符合条件,则填入下一笔。____提前预判
while (y + 1 < n && !a[x][y + 1]) a[x][ ++ y] = ++ cnt;
//向下
while (x + 1 < n && !a[x + 1][y]) a[ ++ x][y] = ++ cnt;
//向左
while (y - 1 >= 0 && !a[x][y - 1]) a[x][ -- y] = ++ cnt;
//向上
while (x - 1 >= 0 && !a[x - 1][y]) a[ -- x][y] = ++ cnt;
}
for (int i = 0; i < n; i ++ )
{
for (int j = 0; j < n; j ++ )
{
// cout << a[i][j] << " ";
printf("%-5d", a[i][j]);
}
cout << endl;
}
cout << endl;
}
return 0;
}
AC代码(756. 蛇形矩阵)
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
const int maxn = 150;
int a[maxn][maxn];
int main()
{
int n, m;
cin >> n >> m;
memset(a, 0, sizeof(a));
int x = 0, y = 0; //初始坐标坐标,(0,0)
int cnt = 1; //初始化第一个数
a[x][y] = cnt;
while (cnt < n * m )
{
//用下一笔的位置来判断
//向右, 符合条件,则填入下一笔。____提前预判
while (y + 1 < m && !a[x][y + 1]) a[x][ ++ y] = ++ cnt;
//向下
while (x + 1 < n && !a[x + 1][y]) a[ ++ x][y] = ++ cnt;
//向左
while (y - 1 >= 0 && !a[x][y - 1]) a[x][ -- y] = ++ cnt;
//向上
while (x - 1 >= 0 && !a[x - 1][y]) a[ -- x][y] = ++ cnt;
}
for (int i = 0; i < n; i ++ )
{
for (int j = 0; j < m; j ++ )
{
cout << a[i][j] << " ";
// printf("%-5d", a[i][j]);
}
cout << endl;
}
return 0;
}
——————————
END
今日份好听,一首纯音乐
——————————