螺旋
【问题描述】
对于一个 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]);
}
}