[C++] 螺旋矩阵--待完善 →→→→→进入此内容的聊天室

来自 , 2020-03-11, 写在 C++, 查看 120 次.
URL http://www.code666.cn/view/7f16109f
  1. void SpiralMatrix(int height, int width, int startNum, int startPos)
  2. {
  3.         int** martix = new int* [height];
  4.         for (int i=0; i<height; i++)
  5.         {
  6.                 *(martix+i) = new int[width];
  7.         }
  8.  
  9.         int loop = 0;
  10.         int totalCnt = height*width;
  11.         if (height == 2 || width == 2)
  12.         {
  13.                 loop = 2;
  14.         }
  15.         else
  16.         {
  17.                 int heightLoop = height/2 + 1;
  18.                 int widthLoop = width/2 + 1;
  19.                 loop = heightLoop<width?heightLoop:widthLoop;
  20.         }
  21.         int x = 0, y=0;
  22.         for (int round=0; round<loop; round++)
  23.         {
  24.                 int widthEnd = width - 1 - round;
  25.                 int heightEnd = height - 1 - round;
  26.                 for (x=round; x<=widthEnd; x++)
  27.                 {
  28.                         *(*(martix+round)+x) = startNum++;
  29.                 }
  30.                 for (y=round+1; y<=heightEnd; y++)
  31.                 {
  32.                         *(*(martix+y)+widthEnd) = startNum++;
  33.                 }
  34.                 if (startNum > totalCnt)
  35.                 {
  36.                         break;
  37.                 }
  38.                 for (x=widthEnd-1; x>=round; x--)
  39.                 {
  40.                         *(*(martix+heightEnd)+x) = startNum++;
  41.                 }
  42.                 for (y=heightEnd-1; y>round; y--)
  43.                 {
  44.                         *(*(martix+y)+round) = startNum++;
  45.                 }
  46.         }
  47.         for (y=0; y<height; y++)
  48.         {      
  49.                 for (x=0; x<width; x++)
  50.                 {
  51.                         cout<<*(*(martix+y)+x)<<" ";
  52.                 }
  53.                 cout<<endl;
  54.         }
  55. }

回复 "螺旋矩阵--待完善"

这儿你可以回复上面这条便签

captcha