蓝桥杯--螺旋矩阵
问题描述
对于一个 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 Main { static int n; static int m; static int art[][] = new int[1005][1005]; static boolean vis[][] = new boolean[1005][1005]; public static boolean ax(int x,int y) { if(x<0 || x>=n ||y<0 ||y>=m || vis[x][y])//越界或者已经被填写 return true; return false; } public static void fun(int x,int y,int t,int f)//当前坐标,当前值,当前方向 0向左,1向下,2向右,3向上 { art[x][y] = t; vis[x][y] = true; if(t== n*m) return; if(f== 0) { if(ax(x, y+1))//不能走 { fun(x+1, y, t+1, 1); } else { fun(x, y+1, t+1, 0); } } else if(f== 1) { if(ax(x+1, y))//不能走 { fun(x, y-1, t+1,2); } else { fun(x+1, y, t+1,1); } } else if(f== 2) { if(ax(x, y-1))//不能走 { fun(x-1, y, t+1,3);//向上走 } else { fun(x, y-1, t+1,2); } } else { if(ax(x-1, y))//不能走 { fun(x, y+1, t+1,0);//向上走 } else { fun(x-1, y, t+1,3); } } } public static void main(String[] args) { // TODO Auto-generated method stub Scanner scanner = new Scanner(System.in); n = scanner.nextInt(); m = scanner.nextInt(); fun(0, 0, 1,0); for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { System.out.print(art[i][j]+" "); } System.out.println(); } } }