答案 0 :(得分:1)
直接的方法可以采用以下方式
#include <stdio.h>
#define N 4
int main(void)
{
int a[N][N] =
{
{ 1, 2, 3, 4 },
{ 11, 12, 13, 14 },
{ 21, 22, 23, 24 },
{ 31, 32, 33, 34 }
};
int k;
printf( "Select a diagonal (%d, %d): ", -N, N );
scanf( "%d", &k );
if ( k < 0 )
{
for ( int i = -k, j = 0; i < N; i++, j++ )
{
printf( "%d ", a[i][j] );
}
}
else
{
for ( int i = 0, j = k; j < N; i++, j++ )
{
printf( "%d ", a[i][j] );
}
}
putchar( '\n' );
return 0;
}
程序输出可能看起来像
Select a diagonal (-4, 4): 2
3 14
或
Select a diagonal (-4, 4): -2
21 32
或者代替带有单独循环的if-else语句,您可以使用一个循环,例如
int i = k < 0 ? -k : 0;
int j = k > 0 ? k : 0;
for ( ; i < N && j < N; i++, j++ )
{
printf( "%d ", a[i][j] );
}
putchar( '\n' );
答案 1 :(得分:-1)
伪代码:
function(martrix, k){
rowmax = matrix.length;
colmax = matrix[0].length;
output = []
for i = 0 to max(rowmax, colmax):
if k > 0 : x = i + k
if k < 0 : y = i + k
if(x < rowmax and y < colmax):
output.append(matrix[x][y])
}