螺旋顺序的二维数组

发布于 2024-07-23 06:28:59 字数 782 浏览 7 评论 0原文

我正在尝试按螺旋顺序填充数组。 到目前为止,我可以按螺旋顺序打印数组,但是有没有办法修改数组,以便我可以按螺旋顺序填充它,然后只打印数组? 我希望它像倒计时一样按降序排列。 请帮忙!

public class Spiral {
  public static void main(int m, int n) { 

    // create m by n array of integers 1 through m*n
    int[][] values = new int[m][n];
    for (int i = 0; i < m; i++)
        for (int j = 0; j < n; j++)
            values[i][j] = 1 + (m*n)*i + j;

    // spiral
    for (int i = (m*n)-1, j = 0; i > 0; i--, j++) {
          for (int k = j; k < i; k++) System.out.println(values[j][k]);
          for (int k = j; k < i; k++) System.out.println(values[k][i]);
          for (int k = i; k > j; k--) System.out.println(values[i][k]);
          for (int k = i; k > j; k--) System.out.println(values[k][j]);
    }
  }
}

I'm trying to fill an array in spiral order. So far, I can print the array in spiral order, but is there a way to modify the array so that i can fill it in spiral order and then just print the array? I'd like it to go in decreasing order like a countdown. Please help!

public class Spiral {
  public static void main(int m, int n) { 

    // create m by n array of integers 1 through m*n
    int[][] values = new int[m][n];
    for (int i = 0; i < m; i++)
        for (int j = 0; j < n; j++)
            values[i][j] = 1 + (m*n)*i + j;

    // spiral
    for (int i = (m*n)-1, j = 0; i > 0; i--, j++) {
          for (int k = j; k < i; k++) System.out.println(values[j][k]);
          for (int k = j; k < i; k++) System.out.println(values[k][i]);
          for (int k = i; k > j; k--) System.out.println(values[i][k]);
          for (int k = i; k > j; k--) System.out.println(values[k][j]);
    }
  }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

千鲤 2024-07-30 06:28:59
int maxValue = target.length * target[0].length;

private int[][] generateMatrix(int[][] target, int level, int currentVal) {
    // always start from lower left corner in each layer
    int w = level;
    int h = target.length - level - 1;

    // fill the bottom line
    int i = 0;
    for (i = w; i < target[0].length - level && currentVal <= maxValue; i++) {
        target[h][i] = currentVal++;
    }

    w = target[0].length - level - 1;

    int j = 0;
    // fill the right line
    for (j = h - 1; j >= level && currentVal <= maxValue; j--) {
        target[j][w] = currentVal++;
    }

    h = level;

    // fill the above line
    for (i = w - 1; i >= level && currentVal <= maxValue; i--) {
        target[h][i] = currentVal++;
    }
    w = level;

    // fill the left line
    for (j = h + 1; j < target.length - level - 1 && currentVal <= maxValue; j++) {
        target[j][w] = currentVal++;
    }

    if (currentVal > maxValue)
        return target;
    return generateMatrix(target, ++level, currentVal);

}
int maxValue = target.length * target[0].length;

private int[][] generateMatrix(int[][] target, int level, int currentVal) {
    // always start from lower left corner in each layer
    int w = level;
    int h = target.length - level - 1;

    // fill the bottom line
    int i = 0;
    for (i = w; i < target[0].length - level && currentVal <= maxValue; i++) {
        target[h][i] = currentVal++;
    }

    w = target[0].length - level - 1;

    int j = 0;
    // fill the right line
    for (j = h - 1; j >= level && currentVal <= maxValue; j--) {
        target[j][w] = currentVal++;
    }

    h = level;

    // fill the above line
    for (i = w - 1; i >= level && currentVal <= maxValue; i--) {
        target[h][i] = currentVal++;
    }
    w = level;

    // fill the left line
    for (j = h + 1; j < target.length - level - 1 && currentVal <= maxValue; j++) {
        target[j][w] = currentVal++;
    }

    if (currentVal > maxValue)
        return target;
    return generateMatrix(target, ++level, currentVal);

}
救赎№ 2024-07-30 06:28:59

下面的函数是一个大小为 N × N 的方阵,包含从 1 到 N * N 的整数,从左上角开始按顺时针方向螺旋排列。

int[][] spiralNumbers(int n) {
int[][] matrix = new int[n][n];
for (int step = 0, a = 0, size; step < n/2; step++) {
    size = (n - step * 2 - 1);
    for (int i = 0, chunk, chunkIndex, chunkOffset; i < 4 * size; i++) {
        chunk = i / size;
        chunkIndex = i % size;
        chunkOffset = n - step - 1;
        switch (chunk) {
            case 0:
                matrix[step][chunkIndex + step] = a+1;
                break;
            case 1:
                matrix[chunkIndex + step][chunkOffset] = a+1;
                break;
            case 2:
                matrix[chunkOffset][chunkOffset - chunkIndex] = a+1;
                break;
            case 3:
                matrix[chunkOffset - chunkIndex][step] = a+1;
                break;
            default:
                throw new IndexOutOfBoundsException();
        }
        a++;
    }
    if (n % 2 == 1) {
        matrix[n/2][n/2] = n * n;
    }
}
return matrix; 
}

Below function is a square matrix with a size N × N containing integers from 1 to N * N in a spiral order, starting from top-left and in clockwise direction.

int[][] spiralNumbers(int n) {
int[][] matrix = new int[n][n];
for (int step = 0, a = 0, size; step < n/2; step++) {
    size = (n - step * 2 - 1);
    for (int i = 0, chunk, chunkIndex, chunkOffset; i < 4 * size; i++) {
        chunk = i / size;
        chunkIndex = i % size;
        chunkOffset = n - step - 1;
        switch (chunk) {
            case 0:
                matrix[step][chunkIndex + step] = a+1;
                break;
            case 1:
                matrix[chunkIndex + step][chunkOffset] = a+1;
                break;
            case 2:
                matrix[chunkOffset][chunkOffset - chunkIndex] = a+1;
                break;
            case 3:
                matrix[chunkOffset - chunkIndex][step] = a+1;
                break;
            default:
                throw new IndexOutOfBoundsException();
        }
        a++;
    }
    if (n % 2 == 1) {
        matrix[n/2][n/2] = n * n;
    }
}
return matrix; 
}
飘过的浮云 2024-07-30 06:28:59

如果您已经找到了执行读取(用于打印)的代码,那么您肯定可以使用相同的逻辑修改它来执行写入操作?

如果您希望矩阵中的每个单元格都包含其“顺序号”,向后计数,假设您的访问逻辑是正确的,类似这样的事情应该可以工作:

for (int i = (m*n)-1, j = 0, index = m * n; i > 0; i--, j++) {
      for (int k = j; k < i; k++) values[j][j] = index--;
      for (int k = j; k < i; k++) values[k][i] = index--;
      for (int k = i; k > j; k--) values[i][k] = index--;
      for (int k = i; k > j; k--) values[k][j] = index--;
}

If you've figured out code to do the reads (for printing), then surely you can just modify that to do writes instead, using the same logic?

If you want each cell in the matrix to contain its "sequential number", counting backwards, something like this ought to work, assuming your access logic is correct:

for (int i = (m*n)-1, j = 0, index = m * n; i > 0; i--, j++) {
      for (int k = j; k < i; k++) values[j][j] = index--;
      for (int k = j; k < i; k++) values[k][i] = index--;
      for (int k = i; k > j; k--) values[i][k] = index--;
      for (int k = i; k > j; k--) values[k][j] = index--;
}
江南烟雨〆相思醉 2024-07-30 06:28:59

不是最有效的,但它应该可以工作:g 是数组。 我还使用异常来控制逻辑。

public static void spiralFill()
{
    x = (g.length-1)/2;
    y = (g[0].length-1)/2;

    try
    {
        while(true)
        {
             east();
             south();
             step++;
             west();
             north();
             step++;        
        }
    }
    catch(ArrayIndexOutOfBoundsException e)
    {

    }
}

public static void east()
{
for(int i = 0; i < step; i++)
{
        g[x][y] = count;
        count++;
    x++;
    }
}
public static void south()
{
    for(int i = 0; i < step; i++)
    {
        g[x][y] = count;
        count++;
        y--;
    }
}   
public static void west()
{
    for(int i = 0; i < step; i++)
    {
         g[x][y] = count;
         count++;
         x--;
    }
}   
public static void north()
{
   for(int i = 0; i < step; i++)
   {
       g[x][y] = count;
       count++;
       y++;
   }
}   

Not the most efficient, but it should work: g is the array. I'm also using exceptions to control logic.

public static void spiralFill()
{
    x = (g.length-1)/2;
    y = (g[0].length-1)/2;

    try
    {
        while(true)
        {
             east();
             south();
             step++;
             west();
             north();
             step++;        
        }
    }
    catch(ArrayIndexOutOfBoundsException e)
    {

    }
}

public static void east()
{
for(int i = 0; i < step; i++)
{
        g[x][y] = count;
        count++;
    x++;
    }
}
public static void south()
{
    for(int i = 0; i < step; i++)
    {
        g[x][y] = count;
        count++;
        y--;
    }
}   
public static void west()
{
    for(int i = 0; i < step; i++)
    {
         g[x][y] = count;
         count++;
         x--;
    }
}   
public static void north()
{
   for(int i = 0; i < step; i++)
   {
       g[x][y] = count;
       count++;
       y++;
   }
}   
相守太难 2024-07-30 06:28:59

以下是一些变化:

public class SpiralMatrix {

    private static int[][] createSpiralMatrix(int size) {
        int[][] matrix = new int[size][size];

        int row = 0, col = -1;
        int value = 1;

        boolean horizontal = true;
        boolean increasing = true;
        boolean finish = false;

        while(!finish) {

            finish = true;
            if (horizontal && increasing) {
                while(tryAndSet(matrix, row, col + 1, value)) {
                    finish = false;
                    col++;
                    value++;
                }
            } else if (horizontal && !increasing) {
                while(tryAndSet(matrix, row, col - 1, value)) {
                    finish = false;
                    col--;
                    value++;
                }
            } else if (!horizontal && increasing) {
                while(tryAndSet(matrix, row + 1, col, value)) {
                    finish = false;
                    row++;
                    value++;
                }
            } else {
                while(tryAndSet(matrix, row - 1, col, value)) {
                    finish = false;
                    row--;
                    value++;
                }
            }

            if (!horizontal) {
                increasing = !increasing;
            }
            horizontal = !horizontal;
        }

        return matrix;
    }


    private static boolean tryAndSet(int[][] matrix, int row, int col, int value) {
        if (row < 0 || col < 0 || row >= matrix.length || col >= matrix[row].length || matrix[row][col] != 0) {
            return false;
        }
        matrix[row][col] = value;
        return true;
    }

    private static void printMatrix(int[][] matrix) {
        for (int i = 0; i < matrix.length; i++) {
            for(int j = 0; j < matrix[i].length; j++) {
                System.out.print("\t" + matrix[i][j]);
            }
            System.out.println();
        }
    }


    public static void main(String[] args) {
        try {
            int[][] spiralMatrix = createSpiralMatrix(40);
            printMatrix(spiralMatrix);
        } catch (Throwable th) {
            th.printStackTrace();
        }
    }

Here is some of the variations:

public class SpiralMatrix {

    private static int[][] createSpiralMatrix(int size) {
        int[][] matrix = new int[size][size];

        int row = 0, col = -1;
        int value = 1;

        boolean horizontal = true;
        boolean increasing = true;
        boolean finish = false;

        while(!finish) {

            finish = true;
            if (horizontal && increasing) {
                while(tryAndSet(matrix, row, col + 1, value)) {
                    finish = false;
                    col++;
                    value++;
                }
            } else if (horizontal && !increasing) {
                while(tryAndSet(matrix, row, col - 1, value)) {
                    finish = false;
                    col--;
                    value++;
                }
            } else if (!horizontal && increasing) {
                while(tryAndSet(matrix, row + 1, col, value)) {
                    finish = false;
                    row++;
                    value++;
                }
            } else {
                while(tryAndSet(matrix, row - 1, col, value)) {
                    finish = false;
                    row--;
                    value++;
                }
            }

            if (!horizontal) {
                increasing = !increasing;
            }
            horizontal = !horizontal;
        }

        return matrix;
    }


    private static boolean tryAndSet(int[][] matrix, int row, int col, int value) {
        if (row < 0 || col < 0 || row >= matrix.length || col >= matrix[row].length || matrix[row][col] != 0) {
            return false;
        }
        matrix[row][col] = value;
        return true;
    }

    private static void printMatrix(int[][] matrix) {
        for (int i = 0; i < matrix.length; i++) {
            for(int j = 0; j < matrix[i].length; j++) {
                System.out.print("\t" + matrix[i][j]);
            }
            System.out.println();
        }
    }


    public static void main(String[] args) {
        try {
            int[][] spiralMatrix = createSpiralMatrix(40);
            printMatrix(spiralMatrix);
        } catch (Throwable th) {
            th.printStackTrace();
        }
    }
吹泡泡o 2024-07-30 06:28:59
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));
              }
         }

       else if(m==1 && n==1){
             result.add(a.get(0).get(0));
         }

     // Populate result;
     return result;

}

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));
              }
         }

       else if(m==1 && n==1){
             result.add(a.get(0).get(0));
         }

     // Populate result;
     return result;

}

玻璃人 2024-07-30 06:28:59

这是我对此的看法:

public class SpiralMatrix {
public static void main(String[] args) {
    int[][] matrix = new int[5][5];
    int startRow = 0;
    int endRow = matrix.length - 1;
    int startCol = 0;
    int endCol = matrix.length - 1;
    int counter = 1;
    int cycleEnder = matrix.length * matrix.length;


    while (counter <= cycleEnder) {

        //FIRST ROW
        for (int i = 0; i <= endCol; i++) {
            matrix[startRow][i] = counter;
            counter++;
        }
        startRow++;
        //RIGHT-SIDE COL
        for (int i = startRow; i <= endRow; i++) {
            matrix[i][endCol] = counter;
            counter++;
        }
        endCol--;
        //BOTTOM ROW REVERSE
        for (int i = endCol; i >= startCol; i--) {
            matrix[endRow][i] = counter;
            counter++;
        }
        endRow--;

        //FIRST COL UP
        for (int i = endRow; i > startRow; i--) {
            matrix[i][startCol] = counter;
            counter++;
        }
        startCol++;


    }
    for (int[] ints : matrix) {
        for (int j = 0; j < matrix.length; j++) {
            if (ints[j] < 10) {
                System.out.print(ints[j] + "  ");
            } else {
                System.out.print(ints[j] + " ");
            }

        }
        System.out.println();
    }
}


    public static void showMatrix ( int[][] mat, int x, int y){
        for (int i = 0; i < mat.length; i++) {
            for (int j = 0; j < mat.length; j++) {
                System.out.print(mat[i][j] + " ");
            }
            System.out.println();
        }
    }
}

Here's my take on this:

public class SpiralMatrix {
public static void main(String[] args) {
    int[][] matrix = new int[5][5];
    int startRow = 0;
    int endRow = matrix.length - 1;
    int startCol = 0;
    int endCol = matrix.length - 1;
    int counter = 1;
    int cycleEnder = matrix.length * matrix.length;


    while (counter <= cycleEnder) {

        //FIRST ROW
        for (int i = 0; i <= endCol; i++) {
            matrix[startRow][i] = counter;
            counter++;
        }
        startRow++;
        //RIGHT-SIDE COL
        for (int i = startRow; i <= endRow; i++) {
            matrix[i][endCol] = counter;
            counter++;
        }
        endCol--;
        //BOTTOM ROW REVERSE
        for (int i = endCol; i >= startCol; i--) {
            matrix[endRow][i] = counter;
            counter++;
        }
        endRow--;

        //FIRST COL UP
        for (int i = endRow; i > startRow; i--) {
            matrix[i][startCol] = counter;
            counter++;
        }
        startCol++;


    }
    for (int[] ints : matrix) {
        for (int j = 0; j < matrix.length; j++) {
            if (ints[j] < 10) {
                System.out.print(ints[j] + "  ");
            } else {
                System.out.print(ints[j] + " ");
            }

        }
        System.out.println();
    }
}


    public static void showMatrix ( int[][] mat, int x, int y){
        for (int i = 0; i < mat.length; i++) {
            for (int j = 0; j < mat.length; j++) {
                System.out.print(mat[i][j] + " ");
            }
            System.out.println();
        }
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文