蓝桥杯2020模拟赛第2场(部分)

螺旋

【问题描述】
对于一个 n 行 m 列的表格,我们可以使用螺旋的方式给表格依次填上正整数,我们称填好的表格为一个螺旋矩阵。
例如,一个 4 行 5 列的螺旋矩阵如下:
1 2 3 4 5
14 15 16 17 6
13 20 19 18 7
12 11 10 9 8
【输入格式】
输入的第一行包含两个整数 n, m,分别表示螺旋矩阵的行数和列数。
第二行包含两个整数 r, c,表示要求的行号和列号。
【输出格式】
输出一个整数,表示螺旋矩阵中第 r 行第 c 列的元素的值。
【样例输入】
4 5
2 2
【样例输出】
15
【评测用例规模与约定】
对于 30% 的评测用例,2 <= n, m <= 20。
对于 70% 的评测用例,2 <= n, m <= 100。
对于所有评测用例,2 <= n, m <= 1000,1 <= r <= n,1 <= c <= m

import java.util.Scanner;

public class LuoXuan {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner s=new Scanner(System.in);
		int n=s.nextInt();
		int m=s.nextInt();
		int r=s.nextInt();
		int c=s.nextInt();
		int top =0;
		int right=m-1;
		int bottom=n-1;
		int left=0;
		int[][]a=new int[n][m];
		int key=0;
		while(top<=bottom && left<=right){
			for(int i=left;i<=right;i++){
				a[top][i]=++key;
			}
			top++;
			
			if(top>bottom)break;
			
			for(int i=top;i<=bottom;i++){
				a[i][right]=++key;
				
			}
			right--;
			for(int i=right;i>=left;i--){
				a[bottom][i]=++key;
			}
			bottom--;
			
			if(left>right)break;
			
			for(int i=bottom;i>=top;i--){
				a[i][left]=++key;
			}
			left++;
		}
		for(int i=0;i<n;i++){
			for(int j=0;j<m;j++){
				System.out.print(a[i][j]+" ");
			}
			System.out.println();
		}
		System.out.print(a[r-1][c-1]);
	}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值