螺旋队列问题

来源:互联网 发布:c语言 逗号分隔符 编辑:程序博客网 时间:2024/05/16 12:28

一、

程序员面试宝典的一道题目:关于螺旋队列问题。设1点的坐标为(0,0) ,x方向向右为正,y方向向下为正,7为(-1,-1),2的坐标为(1,0),3的坐标为(1,1);编程实现输入任意一点坐标(x,y),输出对应的数字。

21  22 …

20   7   8  9   10

19   6   1  2   11

18   5   4  3    2

17  16  15  14   13

如上图可以观察一般规律,1为第0圈,9为第1圈,所以每个圈数的最大值为(2*c+1)^2;再以1为参照点,分别分析上下左右的规律:

上:max + y 根据偏移量,上面的数为:max + y +x

下:max - 5*y 下面的数为:max - 5*y – x

左:max +3*x 左面的数为:max +3*x –y

右:max – 7*x 右面的数为:max – 7*x +y

所以根据上面的分析,代码如下:

publicclass Test {

  /*

   *上:max + y 根据偏移量,上面的数为:max + y+x下:max - 5*y下面的数为:max -5*y – x

   *左:max +3*x 左面的数为:max +3*x–y 右:max – 7*x 右面的数为:max –7*x +y

   *所以根据上面的分析,代码如下:

   */

  publicstatic  int  cal(int x,int y){

     //计算圈数的最大值

     int c=Math.abs(x)>Math.abs(y)?x:y;

     int result=x;

     c=Math.abs(c);

     intmax=(2*c+1)*(2*c+1);

     if(c!=0){

       if(x==c){//在右边

         result=max - 7*x +y;

       }

       if(x==-c){//在左边

         result=max +3*x -y;

       }

       if(y==c){//在下面

         result=max - 5*y-x;

       }

       if(y==-c){//在上面

         result=max + y +x;

       }

     }

     return result;

  }

      publicstatic voidmain(String[] args) {

       //螺旋队列问题

       System.out.println(cal(2,3));

     }

}

 二、

有时候还会考下面的题目:

打印输出下面的矩阵

1     2    3     4    5

16  17  18   19   6

15   24  25   20  7

14   23  22   21  8

13  12   11   10  9

public class Test {
/*  1   2   3    4    5
16  17  18   19   6
15  24  25   20   7
14  23  22   21   8
13  12  11   10   9
这题和LeetCode的一个岛屿差不多,直接从上下左右考虑好循环就好了*/

public static  void  cal(int a[][],int n)
{
int j;
int m=1;
for(int i=0;i<n/2;i++){
//右面
for(j=0;j<n-i;j++){
if(a[i][j]==0)
a[i][j]=m++;
}
//下面
for(j=i+1;j<n-i;j++){
if(a[j][n-i-1]==0)
a[j][n-i-1]=m++;
}
//左面
for(j=n-i-1;j>i;j--){
if(a[n-i-1][j]==0)
a[n-i-1][j]=m++;
}
//上面
for(j=n-i-1;j>i;j--){
if(a[j][i]==0)
a[j][i]=m++;
}
}
if(n%2==1){
a[n/2][n/2]=m;
}


}
   public static void main(String[] args) {
//螺旋队列问题
  int a[][]=new int[10][10];
  for(int i=0;i<10;i++){
    for(int j=0;j<10;j++){
    a[i][j]=0;
    }
    }
  cal(a,5);
    for(int i=0;i<5;i++){
    for(int j=0;j<5;j++){
    System.out.println(a[i][j]);
    }
    }
}
}

 

 

0 0
原创粉丝点击