由数字围绕矩形按顺时针方向移动组成的图案(长度和宽度每次递减)

Pattern consisting of numbers moving in clockwise direction around a rectangular shape (length and breadth decreasing each time)

本文关键字:数字 顺时针 移动 方向      更新时间:2023-10-16

我已经为许多模式编写了代码,但无法为这个.....编写甚至没有得到任何提示如何继续。

我想生成以下输出:

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

…其中矩形的宽度和高度被指定为输入

我会这样做:

初始化一个5x5的二维整数数组为0。有一个direction变量,并为四个方向定义常数或enum。从(0,0)开始向右移动,用递增的值填充数组,直到到达边缘或非0的数字。然后,增加方向(和wrap)并继续。然后以行为单位打印数组。

使用循环的另一种方法是遍历所有(x, y)坐标,并将x和y传递给一个函数,该函数给出该位置的值。我写的函数和填充数组的函数做的事情完全一样,除了它不写入数组,当它到达给定的(x, y)时,它返回当前值。虽然效率不高,但还是达到了效果。

既然这是一个家庭作业问题,我就给你一个提示——从写这个函数开始:

void predecessor(int in_x, int in_y, int& out_x, int& out_y);

我就不多说了——由你来弄清楚这个函数是用来做什么的:)

我将创建4个单独的循环。

循环1将创建1 2 3 4 5
循环2将创建6 7 8 9
循环3将创建10 11 12 13
循环4将创建14 15 16

完成后,您已经填满了正方形的外部,并留下一个较小的3x3正方形,可以以完全相同的方式填充,使用完全相同的4个循环。

这是我自己想出来的,代码是逆时针的,但你可以通过改变方向数组来改变它。

int x = 0;
int y = 0;
int c = width * height;
int directions[4] = { 0, 1, 0, -1};
int distances[2] = { height, width-1};
int di = 0;
int dx = directions[ di];
int dy = directions[ di+1];
int dis = distances[ di];
for( int i=0; i<c; i++)
{
    value = data[ y * width + x] = i;
    dis--;
    if( dis == 0)
    {
        distances[ di % 2]--;
        di++;
        dx = directions[ di % 4];
        dy = directions[ (di+1) %4];
        dis = distances[ di % 2];
    }
    x += dx;
    y += dy;
}
#include <stdio.h>
#include <stdlib.h>
#define SIZE 5
#define RIGHT 1
#define DOWN 2
#define LEFT 3
#define UP 4

void printArray1(int b[SIZE][SIZE], int size);
void printArray2(int b[SIZE][SIZE], int size);
int move(int b[SIZE][SIZE], int *xpos, int *ypos, int *movem, int number);

int main(void) {

    int i, j, num;
    int dir;
    int a[SIZE][SIZE] = { 0 }; 
    printArray1(a, SIZE);
    printf("nn");
    printArray2(a, SIZE);
    dir = RIGHT;
    i = 0;
    j = 0;
    num = 1;
    for (; num <= (SIZE * SIZE); num++ )
        move(a, &i, &j, &dir, num);
    printArray1(a, SIZE);
    printf("nn");
    printArray2(a, SIZE);
    return 0;
}


void printArray1 (int b[SIZE][SIZE], int size)
{
    int i, j;
    for ( i = 0; i < size; i++ ) {
        for ( j = 0; j < size; j++ )
            printf("%3d  ", b[j][i]);
        printf("n");
    }
    printf("nn");
    return;
}
void printArray2 (int b[SIZE][SIZE], int size)
{
    int i, j;
    for ( i = 0; i < size; i++ ) {
        for ( j = 0; j < size; j++ )
            printf("%3d  ", b[i][j]);
        printf("n");
    }
    printf("nn");
    return;
}

int move(int b[SIZE][SIZE], int *xpos, int *ypos, int *movem, int number)
{
    int x, y, dirn, reqdDirn;
    x = *xpos;
    y = *ypos;
    dirn = *movem;
    if (b[x][y] == 0 ) {
        b[x][y] = number;
    }

    reqdDirn = dirn;
    switch (dirn) {
    default:
        printf("Unexpected value");
        return;
    case RIGHT:
        x = x + 1;
        if (b[x][y] == 0) {
            if (x > SIZE-1) {
                reqdDirn = DOWN;
                x = SIZE - 1;
                y = y + 1;
                if (y > SIZE-1)
                    y = SIZE - 1;
            }
        } else {
            // just step back and change direction
            x = x - 1;
            y = y + 1;
            reqdDirn = DOWN;
        }
        break;
    case DOWN:
        y = y + 1;
        if (b[x][y] == 0) {
            if (y > SIZE-1) {
                reqdDirn = LEFT;
                y = SIZE - 1;
                x = x - 1;
                if (x < 0)
                    x = 0;
            }
        } else {
            y = y - 1;
            x = x - 1;
            reqdDirn = LEFT;
        }
        break;
    case LEFT:
        x = x - 1;
        if (b[x][y] == 0) {
            if (x < 0) {
                reqdDirn = UP;
                x = 0;
                y = y - 1;
                if (y < 0)
                    y = 0;
            }
        } else {
            // just step back and change direction
            x = x + 1;
            y = y - 1;
            reqdDirn = UP;
        }
        break;
    case UP:
        y = y - 1;
        if (b[x][y] == 0) {
            if (y < 0) {
                reqdDirn = RIGHT;
                y = 0;
                x = x + 1;
                if (x > SIZE-1)
                    x = SIZE - 1;
            }
        } else {
            // just step back and change direction
            y = y + 1;
            x = x + 1;
            reqdDirn = RIGHT;
        }
        break;
    }

    *xpos = x;
    *ypos = y;
    *movem = reqdDirn;
}

 Output
  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  


  1   16   15   14   13  
  2   17   24   23   12  
  3   18   25   22   11  
  4   19   20   21   10  
  5    6    7    8    9  

//java
包ds1;

public class SpiralMatrix {
    public static void main(String[] args) throws Exception{
          int[][] values = {{1,2,3,4,5}, {6,7,8,9,10}, {11,12,13,14,15},{16,17,18,19,20},{21,22,23,24,25}};
            int x=0,y=0,z=0 ,length=values.length;
            System.out.println("Jai ShRaam n array size :"+length+" n n");
        //Logic Starts
        for (int i=0;i<values.length;i++ )
        {
            for (int j=0;j<values.length;j++ )
            {
                if(i==j){
                            for(int k=i;k<length-i;k++)
                            {
                                System.out.print(values[x][k]+" , ");
                            }
                            x++;y++;
                            for(int k=x;k<length-i;k++)
                            {
                                System.out.print(values[k][length-x]+" ; ");
                            }
                            y++;
                            for(int k=i+length-y;k>=i;k--)
                            {
                                System.out.print(values[length-x][k]+" - ");
                            }
                            for(int k=i+length-y;k>=x;k--)
                            {
                                System.out.print(values[k][i]+" : ");
                            }
                }//end of i==j
            }//end of j loop
            //System.out.println();
        }
        //Logic ends
    }//end of psvm
}

//答案1,2,3,4,5,10;15;20;25;24 - 23 - 22 - 21 - 16: 11: 6: 7、8、9、14;19;18 - 17 - 12:13,

public ArrayList<Integer> spiralOrder(final List<ArrayList<Integer>> a) {
     ArrayList<Integer> result = new ArrayList<Integer>();
      int m = a.get(0).size();
      int n = a.size();
      if(m>1 && n>1){
         int loopCounter = (n > m)  ? m*2 : n *2 -1 ;
         int opr=1;
         int i=0,j=0;
         int opA=m,opB=n,opC=0,opD=1;
         for(int k=0;k < loopCounter ;k++){
              if(opr == 1){
                 int counter =0;
                 while(counter < opA){
                    System.out.print(a.get(i).get(j)+ ";");
                    result.add(a.get(i).get(j));
                    counter++;
                    if(j != opA-1){
                        j++;
                    }
                    else{
                        break;
                    }
                 }
                 opr =2;
                 continue;
             }
             if(opr == 2){
                 i++;
                 int counter =1;
                 while(counter < opB){
                     System.out.print(a.get(i).get(j)+ ";");
                    result.add(a.get(i).get(j));
                    counter++;
                   if( i != opB-1){
                     i++;
                   }
                   else{
                       break;
                   }
                 }
                 opr =3;
                 continue;
             }
             if(opr == 3){
                 j--;
                 int counter =j;
                 while(counter >= opC){
                     System.out.print(a.get(i).get(j)+ ";");
                    result.add(a.get(i).get(j));
                    counter --;
                     if(j != opC){
                     j--;
                    }
                    else{
                        break;
                    }
                  }
                 opr =4;
                 continue;
             }
             if(opr == 4){
                 i--;
                 int counter = i;
                 while(counter >= opD){
                     System.out.print(a.get(i).get(j)+ ";");
                    result.add(a.get(i).get(j));
                    counter --;
                    if(i != opD){
                     i--;
                    }else{
                        break;
                    }
                 }
                 opr =1;
                 j++;
                 opA = opA -1;
                 opB = opB -1;
                 opC= opC +1;
                 opD = opD+1;
                 continue;
             }
         }
     }
    else if(n ==1){
        for(int k=0;k < a.get(0).size();k++){
            result.add(a.get(0).get(k));
        }
    }
    // Populate result;
    return result;
}

这是我在Java中的解决方案:(我已经知道指针指向内存中的特定地址,或者在C上声明为达到此目的,并且因为Java不支持指针,我用非C指针逻辑这样做了)所以,也就是说,我用指向矩阵的"地址"(rowwn, column)的逻辑这样做了。

static void MatrixTravelPointer(int [][] m){
    int pointerX = 0;
    int pointerY = 0;
    List<Integer> elements = new ArrayList<>();
    int maxlength_ = 0;
    int pos = 0;
    for(int i=0;i<m.length;i++){
        maxlength_ +=m[i].length;
    }
    boolean turn = false;
    int turns = 1;
    while(pos<maxlength_)
    {
        System.out.print(" "+m[pointerX][pointerY]);
        elements.add(m[pointerX][pointerY]);
        if( (pointerY == m[0].length - turns && pointerX == m.length - turns)){
            turn = true;
            turns++;
        }
        if(turns > 1 && turn == true && pointerX == turns - 1){
            turn = false;
        }
        if(turn == false){
            if(pointerY < m[0].length - turns){
                pointerY++;
            } else if(pointerX < m.length - turns){
                pointerX++;
            }
        }
        if(turn == true)
        {
            if(pointerY >= turns - 1){
                pointerY--;
            } else if(pointerX >= turns - 1){
                pointerX--;
            }
        }
        pos++;
    }
    System.out.print("n");
    Iterator it = elements.iterator();
    while(it.hasNext()){
        System.out.print(" "+(int)it.next());
    }
} 

目前我的逻辑只适用于立方矩阵和矩形矩阵。
使用4x4矩阵的逻辑是这样的:
指针在矩阵中从[0][0]移动到[0][3],此时它将移动指针从[0][3]移动到[3],想象一下《俄罗斯方块》中的一个自上而下的"L",此时我们可以省略或删除顶部行和右侧列,并使用从右到左和从下到上的方法反转移动点。因为每次我们在"第二次转弯"上形成一个"L",我们都需要根据我们形成"L"的次数来减少"转弯"的大小("L"的大小)。

package arrays;
public class SpiralPrinting {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int[][] a = new int[][] { { 1, 2, 3 }, { 5, 6, 7 }, { 9, 10, 11 },
                { 13, 14, 15 } };
        int cols = a[0].length;
        int rows = a.length;
        Business1 b = new Business1();
        b.print(a, rows, cols);
    }
}
class Business1 {
    int i = 0;
    int j = 0;
    int count = 0;
    public void print(int[][] a, int row, int col) {
        int max = row * col;
        while (count < max) {
            for (int k = 0; k < col; k++) {
                System.out.println(a[i][j]);
                j++;
                count++;
            }
            row--;
            j--;
            i++;
            for (int k = 0; k < row; k++) {
                System.out.println(a[i][j]);
                i++;
                count++;
            }
            i--;
            j--;
            col--;
            for (int k = 0; k < col; k++) {
                System.out.println(a[i][j]);
                j--;
                count++;
            }
            row--;
            j++;
            i--;
            for (int k = 0; k < row; k++) {
                System.out.println(a[i][j]);
                i--;
                count++;
            }
            i++;
            j++;
            col--;
        }
    }
}