蛇形填数
蛇形填数
题目
题目描述
本题为填空题,只需要算出结果后,在代码中使用输出语句将所填结果输出即可。
如下图所示,小明用从 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(); } } }