寒假每日一题打卡day13——AcWing 754. 平方矩阵 II

【题目描述】
寒假每日一题打卡day13——AcWing 754. 平方矩阵 II

AcWing 754. 平方矩阵 II

模拟

import java.io.*;
class Main{
    public static void main(String args[]) throws Exception{
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        while(true){
            int n = Integer.parseInt(bf.readLine());
            if( n  == 0)  break;
            int q[][] = new int [n][n];
            
            //对角线元素位置(x,x)
            int x = 0;
            while(x != n ){
                int a = 1;
                for(int i = x; i < n; i++){
                    //以(x,x)为起点自左向右填
                    q[x][i] = a;
                    //以(x,x)为起点自上向下填
                    q[i][x] = a;
                    a += 1;
                }
                x += 1;
            }
            for(int i = 0 ; i < n; i++){
                for(int j = 0; j < n; j++){
                    System.out.print(q[i][j]+" ");
                }
                System.out.println();
            }
            System.out.println();
        }
    }
}

使用增量数组

import java.io.*;
class Main{
    //方向增量数组  右、下
    static int dx[]={0, 1}, dy[] ={1, 0};
    public static void main(String args[]) throws Exception{
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        while(true){
            int n = Integer.parseInt(bf.readLine());
            if( n  == 0 )  break;
            int q[][] = new int [n][n];
     
            //起点
            int sx = 0, sy =0;
            while( sx < n){
                
                //先往右走
                int d = 0, a = 1;
                q[sx][sy] = a;
                int nx = sx + dx[d], ny = sy + dy[d];
                while( ny < n) {
                    q[nx][ny] = ++a;
                    nx = nx + dx[d];
                    ny = ny + dy[d];
                }
                
                //改变方向 往下走
                d = 1;
                
                //计数器重新从1开始
                a = 2;
                nx = sx + dx[d];
                ny = sy + dy[d];
                while( nx < n) {
                    q[nx][ny] = a++;
                    nx = nx + dx[d];
                    ny = ny + dy[d];
                }
                
                //更改起点
                sx += 1;
                sy += 1;
            }
       
            
            for(int i = 0 ; i < n; i++){
                for(int j = 0; j < n; j++){
                    System.out.print(q[i][j]+" ");
                }
                System.out.println();
            }
            System.out.println();
        }
    }
}
上一篇:数据分析任务五——作者信息关联


下一篇:对接海康AI Cloud智能应用平台