// SpiralMatrix_2016_1.cpp : 定义控制台应用程序的入口点。
//2016年1月份螺旋矩阵! X-Bag编写
#include "stdafx.h"
#include
#include
#include
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
while (1)
{
int** array;
int m, n;
int step = 1;
int point = 1;
enum enumType { DOWN, RIGHT, UP, LEFT }MOVE = DOWN; //定义行走方向! 初始方向向下走!
cout << "请输入行数:";
cin >> m;
cout << endl;
cout << "请输入列数:";
cin >> n;
cout << endl;
//动态分配m行n列的二维数组空间---------------------------
array = (int**)malloc(sizeof(int*)*m);
for (int i = 0; i < m; i++)
{
array[i] = (int*)malloc(sizeof(int)*n);
}
//动态数组赋值从1到m*n-----------------------------------
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
array[i][j] = point++;
}
}
//动态数组数据打印测试-----------------------------------
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
cout << array[i][j] << "\t";
}
cout << endl;
}
//螺旋矩阵按步走------------------------------------------
int x = n, y = m;//这个是步长控制,在x方向可走n步,y方向可走m步
int i = 0, j = 0;
while (step <= m*n)//循环结束条件
{
switch (MOVE)
{
case DOWN: //向下走
{
for (int k = 0; k < y; k++)
{
array[i][j] = step++;
i++;
}
i--, j++;
MOVE = RIGHT;
x--;
}
break;
case RIGHT:
{
for (int k = 0; k < x; k++)
{
array[i][j] = step++;
j++;
}
j--, i--;
MOVE = UP;
y--;
}
break;
case UP:
{
for (int k = 0; k < y; k++)
{
array[i][j] = step++;
i--;
}
i++, j--;
MOVE = LEFT;
x--;
}
break;
case LEFT:
{
for (int k = 0; k < x; k++)
{
array[i][j] = step++;
j--;
}
j++, i++;
MOVE = DOWN;
y--;
}
break;
default:
break;
}
}
//螺旋矩阵排序打印------------------------------------------
cout <
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
cout << array[i][j] << "\t";
}
cout << endl;
}
//释放动态开辟的二位数组空间
for (int i = 0; i < m; i++)
{
free(array[i]);
}
free(array);
}
system("pause");
return 0;
}
交作业去吧!
学C有用吗?
学C++有前途吗?
数据库有必要学吗?
……
别问,你还什么都不会,学就对了
……