• Java 第十一届 蓝桥杯 省模拟赛 螺旋矩阵


    螺旋矩阵

    题目
    问题描述

    对于一个 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。

    PS:

    小编做的南墙做的LeetCode类似题可以去看看,leetcode的题是取数,这个是放数,然后取某一个位置的
    有问题直接去LeetCode 54 官网的题官方题解和评论帮你解决一切

    package 省模拟赛;
    
    import java.util.Scanner;
    
    public class 螺旋矩阵 {
    	public static void main(String[] args) {
    		Scanner sc = new Scanner(System.in);
    		int n = sc.nextInt();
    		int m = sc.nextInt();
    		int x = sc.nextInt();
    		int y = sc.nextInt();
    		sc.close();
    		int[][] num = new int[m][n];
    		int temp=1;
    		 int upBound = 0;
    	        int rightBound = num[0].length-1;
    	        int leftBound = 0;
    	        int downBound = num.length-1;
    	        while(true){
    	        	//1000*1000复杂度应该不会超时 
    	            //四个方向放数,上下左右四个循环
    	            //上面放最上面一行的,下面最下面一行的,如果放完数的话就可以pass这一层了
    	            for(int i=leftBound; i<=rightBound; ++i)    
    	                num[upBound][i]=temp++;
    	            if(++upBound>downBound) break;
    	            for(int i=upBound; i<=downBound; ++i)   
    	            	num[i][rightBound]=temp++;
    	            if(--rightBound<leftBound)  break;
    	            for(int i=rightBound; i>=leftBound; --i)   
    	            	num[downBound][i]=temp++;
    	            if(--downBound<upBound) break;
    	            for(int i=downBound; i>=upBound; --i)   
    	                 num[i][leftBound]=temp++;
    	            if(++leftBound>rightBound)  break;
    	        }
    	        System.out.println(num[x-1][y-1]);
    	}
    }
    
    
  • 相关阅读:
    滑动条使用
    jquery日历练习
    JQuery 教程
    JS获取各种宽度、高度的简单介绍
    如何获取元素位置
    DOM练习
    DOM
    函数
    假期练习
    Uva 253 Cube painting
  • 原文地址:https://www.cnblogs.com/a1439775520/p/12946214.html
Copyright © 2020-2023  润新知