简单的实现螺旋矩阵

来源:互联网 发布:网络运营推广 编辑:程序博客网 时间:2024/06/03 14:58

16 15 14 13 

 5   4    3  12

 6   1    2  11

 7   8    9  10

const std::vector<std::vector<int>>/*&*/ CAlgorithm::screwMatrix(const int& width, const int&height ){int differ = width - height;if (!(differ == 0 || differ == 1) || width + height < 2){std::vector<std::vector<int>> buff;return buff;}std::vector<int> buff1(width,0);/*static*/ std::vector<std::vector<int>> buff0(height,buff1);int num = 1, start = width / 2 - 1, max = width * height;int j, count, x, y;for (int i = 2; i <= width + 1; i += 2){j = 1;count = 1;//第一次取最里面的2X2的矩阵左上角点为初始点,之后每次把初始点斜向上移一格if (width <= 2){if (height == 1){x = -1;y = 0;}else {x = y = 0;}}else{if (2 == i){if (width % 2 == 0){if (height % 2 == 0){x = start;y = x;}else{x = start - 1;y = start;}}else{x = start;y = start +1;}}else{x -= 1;y -= 1;}}while (j < i){switch(count){case 1: ++x;break;case 2: ++y;break;case 3: --x;break;case 4: --y;break;}buff0[x][y] = num++;if (num > max){break;}j++;if (j >= i && count < 4){count++;j = 1;}}}for (int i = 0; i < height; i++)for(int j = 0; j < width; j++){int temp = buff0[i][j];if(temp < 10)std::cout<<" "<<temp<<" ";elsestd::cout<<temp<<" ";if(j == width - 1)std::cout<<std::endl;}return buff0;}




原创粉丝点击