2d Array in Spiral Order

后端 未结 6 883
失恋的感觉
失恋的感觉 2020-12-20 00:30

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

6条回答
  •  醉酒成梦
    2020-12-20 00:55

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

提交回复
热议问题