平方矩阵II WriteUp
原题链接:
AC源代码:
方法一:找规律
在二维矩阵中:(i,j)=abs(i−j)
#include <iostream>
#include <cmath>
using namespace std;
const int N = 100 ;
int a[N][N];
int main()
{
int n;
while ( cin >> n , n){
for ( int i = 0 ; i < n ; i ++){
for ( int j = 0 ; j < n ; j ++){
cout << abs(i - j) + 1 << " " ;
}
cout << endl;
}
cout << endl;
}
return 0;
}
作者:Lxxx_6
链接:https://www.acwing.com/activity/content/code/content/815190/
来源:AcWing
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
方法二:从左上到右下的对角线的值为1
遍历对角线上的每一个1
,从左
到右
、从上
到下
填充数字。
#include <iostream>
using namespace std;
const int N = 100 ;
int a[N][N];
int main()
{
int n;
while ( cin >> n , n){
for ( int i = 0 ; i < n ; i ++){
a[i][i] = 1;
for ( int j = i + 1 , k = 2 ; j < n ; j ++ , k ++) a[i][j] = k ;
for ( int j = i + 1 , k = 2 ; j < n ; j ++ , k ++) a[j][i] = k ;
}
for ( int i = 0 ; i < n ; i ++){
for ( int j = 0 ; j < n ; j ++){
cout << a[i][j] << " " ;
}
cout << endl;
}
cout << endl;
}
return 0;
}
作者:Lxxx_6
链接:https://www.acwing.com/activity/content/code/content/815190/
来源:AcWing
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。