同行列对角线的格子

GitHub跳转原题关系图返回列表

从目标格沿四个方向定位对角线起点,依次生成同行、列和两条对角线。

OJ: noi_openjudge

题目 ID: ch0108-02

难度:入门

标签:矩阵模拟坐标python

日期: 2026-07-30 23:01

题意

N×NN\times N 棋盘上输出与给定格同行、同列和同两条对角线的格子坐标。

思路

同行和同列直接枚举。主对角线先向左上移动到边界,再按 (+1,+1)(+1,+1) 前进;副对角线先向左下移动到边界,再按 (1,+1)(-1,+1) 前进。

代码

cpp
#include <cstdio>
int a[20][20];
int n,x,y;
int main(){
    scanf("%d%d%d",&n,&x,&y);
    int i,j;
    for (i=1;i<=n;i++){
        printf("(%d,%d) ",x,i);
    }
    printf("\n");

    for (i=1;i<=n;i++){
        printf("(%d,%d) ",i,y);
    }
    printf("\n");
    
    for (i=1;i<=n;i++){
        for (j=1;j<=n;j++){
            if( i-j == x - y){
                printf("(%d,%d) ",i,j);
                break;
            }
        }
    }
    printf("\n");

    for (i=n;i>=1;i--){
        for (j=1;j<=n;j++){
            if( i+j == x + y){
                printf("(%d,%d) ",i,j);
                break;
            }
        }
    }
    printf("\n");
    return 0;
}

复杂度

总结

Python代码

python
size, row, column = map(int, input().split())

def show(cells):
    print(" ".join(f"({x},{y})" for x, y in cells))

show((row, y) for y in range(1, size + 1))
show((x, column) for x in range(1, size + 1))

steps = min(row - 1, column - 1)
start_row, start_column = row - steps, column - steps
show((start_row + offset, start_column + offset) for offset in range(min(size - start_row, size - start_column) + 1))

steps = min(size - row, column - 1)
start_row, start_column = row + steps, column - steps
show((start_row - offset, start_column + offset) for offset in range(min(start_row - 1, size - start_column) + 1))

C++代码

cpp
#include <cstdio>
int a[20][20];
int n,x,y;
int main(){
    scanf("%d%d%d",&n,&x,&y);
    int i,j;
    for (i=1;i<=n;i++){
        printf("(%d,%d) ",x,i);
    }
    printf("\n");

    for (i=1;i<=n;i++){
        printf("(%d,%d) ",i,y);
    }
    printf("\n");
    
    for (i=1;i<=n;i++){
        for (j=1;j<=n;j++){
            if( i-j == x - y){
                printf("(%d,%d) ",i,j);
                break;
            }
        }
    }
    printf("\n");

    for (i=n;i>=1;i--){
        for (j=1;j<=n;j++){
            if( i+j == x + y){
                printf("(%d,%d) ",i,j);
                break;
            }
        }
    }
    printf("\n");
    return 0;
}

复杂度

四条线各至多 NN 个格子,时间复杂度为 O(N)O(N),额外空间复杂度为 O(1)O(1)

总结

对角线输出先找规定方向的边界起点,便能保证题目要求的顺序。