近期写算法最笨蛋的方法了真是😂
简洁版不分上下两种情况 直接将一个正方形拓展面 向右向下分别拓展 以构成一个边长为2n的等腰三角形
拓展面:
#include <iostream>
#include <cstring>
#include <vector>
using namespace std;
const int maxn = 510;
int main()
{
int n;
cin >> n;
int c[maxn][maxn];
for(int i = 0; i < n; i++)
{
for(int j =0; j < n; j++)
{
cin >> c[i][j];
}
}
for(int i = 0; i <= 2 * n -1; i++)// 横纵坐标之和
{
if(i % 2)//奇数向下
{
for(int j = 0; j <= i;j++)
{
if(j >= 0 && j < n && i - j >= 0 && i - j < n) cout << c[j][i-j] << " ";
}
}
else //偶数向上
{
for(int j = i; j >= 0; j--)
{
if(j >= 0 && j < n && i - j >= 0 && i - j < n) cout << c[j][i-j] << " ";
}
}
}
return 0;
}
标志法:
#include <iostream>
#include <cstring>
#include <vector>
using namespace std;
const int maxn = 510;
int main()
{
int n;
cin >> n;
int c[maxn][maxn];
for(int i = 0; i < n; i++)
{
for(int j =0; j < n; j++)
{
cin >> c[i][j];
}
}
int x = 0, y = 0;
bool flag = true;
while(x != n || y != n)
{
if(x < n && y < n) cout << c[x][y] << " ";
if(flag) x--,y++;
else x++,y--;
if(x < 0)
{
x = 0;
flag = !flag;
}
if(y < 0)
{
y = 0;
flag = !flag;
}
}
return 0;
}
笨蛋方法:
#include <iostream>
#include <cstring>
#include <vector>
using namespace std;
const int maxn = 510;
int main()
{
int n;
cin >> n;
int c[maxn][maxn];
for(int i = 0; i < n; i++)
{
for(int j =0; j < n; j++)
{
cin >> c[i][j];
}
}
int x, y;
for(int i = 0; i < n; i++)
{
if(i % 2 == 0) //偶数向上(x,y)
{
x = i;
y = 0;
while(1)
{
cout << c[x][y] << " ";
x--;
y++;
if(x == -1) break;
}
}
else//
{
x = 0;
y = i;
while(1)
{
cout << c[x][y] << " " ;
x++;
y--;
if(y == -1) break;
}
}
}
if(n % 2 == 0)
{
for(int i = 1; i < n; i++)
{
if(i % 2 != 0)
{
x = n-1;
y = i;
while(1)
{
cout << c[x][y] << " ";
x--;
y++;
if(y == n) break;
}
}
else
{
x = i;
y = n-1;
while(1)
{
cout << c[x][y] << " " ;
x++;
y--;
if(x == n) break;
}
}
}
}
else
{
for(int i = 1; i < n; i++)
{
if(i % 2 == 0)
{
x = n-1;
y = i;
while(1)
{
cout << c[x][y] << " ";
x--;
y++;
if(y == n) break;
}
}
else
{
x = i;
y = n-1;
while(1)
{
cout << c[x][y] << " " ;
x++;
y--;
if(x == n) break;
}
}
}
}
return 0;
}