蓝桥杯历年真题题解----2020年-- 蛇形填数

简介: 蓝桥杯历年真题题解----2020年-- 蛇形填数

蛇形填数

蛇形填数

题目

题目描述

本题为填空题,只需要算出结果后,在代码中使用输出语句将所填结果输出即可。

如下图所示,小明用从 1 开始的正整数“蛇形”填充无限大的矩阵。

1 2 6 7 15 …

3 5 8 14 …

4 9 13 …

10 12 …

11 …

容易看出矩阵第二行第二列中的数是 5。请你计算矩阵中第 20 行第 20 列的数是多少?

运行限制

最大运行时间:1s

最大运行内存: 128M

解题思路

模拟填数

填数:

先斜向上填 row–;col++;

到第一行停止

在斜向下填 row++;col–;

到第一列停止

模拟时要计数同时防止下标越界

解题代码

package 蓝桥杯.真题2020;
public class 蛇形填数 {
    public static void main(String[] args) {
        //开大一点防止越界
        int[][] nums = new int[150][150];
        int row = 1;
        int col = 1;
        int cnt = 1;
        while ( true ) {
            //斜向上填数
            while ( row>=1 ) {
                nums[row][col] = cnt;
                row--;
                col++;
                cnt++;
            }
            //处理下标越界
            row = row+1;
            //斜向下填
            while ( col>=1 ) {
                nums[row][col] = cnt;
                row++;
                col--;
                cnt++;
            }
            //处理下标越界
            col = col+1;
            //找到答案
            if ( nums[20][20]>0 ) break;
        }
        //输出数组
        System.out.print( String.format("%5d", 0) );
        for ( int i=1; i<=20; i++ ) {
            System.out.print( String.format("%5d", i) );
        }
        System.out.println();
        for ( int i=1; i<=20; i++ ) {
            System.out.print( String.format("%5d", i) );
            for ( int j=1; j<=20; j++ ) {
                System.out.print( String.format("%5d", nums[i][j]) );
            }
            System.out.println();
        }
    }
}
相关文章
|
2月前
|
传感器
蓝桥杯历年真题题解----2020年-- 子串分值和
蓝桥杯历年真题题解----2020年-- 子串分值和
|
11月前
|
API
蓝桥杯历年真题题解----2020年
蓝桥杯历年真题题解----2020年
蓝桥杯历年真题题解----2020年-- 答疑
蓝桥杯历年真题题解----2020年-- 答疑
蓝桥杯历年真题题解----2020年-- 跑步锻炼
蓝桥杯历年真题题解----2020年-- 跑步锻炼
|
11月前
|
搜索推荐
蓝桥杯历年真题题解----2020年-- 排序
蓝桥杯历年真题题解----2020年-- 排序
|
11月前
|
Java
蓝桥杯历年真题及题解
蓝桥杯历年真题及题解
|
算法 API C++
蓝桥杯历年真题分类汇总(史上最全版本,一定不要错过)
蓝桥杯历年真题分类汇总(史上最全版本,一定不要错过)
蓝桥杯历年真题分类汇总(史上最全版本,一定不要错过)