今天遇到一道面试题,要求输入N,并且构造一个逆时针N*N的旋转矩阵。花了一下午时间写完的,把这个分享给大家。
//构造矩阵的函数,从
int **BuildMatrix(int width)
{
int **pMatrix = new int*[width];
for (int i = 0; i < width; ++i)
{
pMatrix[i] = new int[width];
}
for (int i = 0; i < width; ++i)
for (int j = 0; j < width; ++j)
pMatrix[i][j] = 0;
//剩余宽度计数器
int n = width;
//初始化初始位置的数值
pMatrix[0][0] = 0;
int tempMatrix[6][6] = {};
for (int i = 0; i < width*0.5; ++i)
{
//构建左边
for (int j = i; j < n - 1; ++j)
{
pMatrix[j + 1][i] = pMatrix[j][i] + 1;
}
//构建下边
for (int j = i; j < n - 1; ++j)
{
pMatrix[n - 1][j + 1] = pMatrix[n - 1][j] + 1;
}
//构建右边
for (int j = n - 1; j > i; --j)
{
pMatrix[j - 1][n - 1] = pMatrix[j][n - 1] + 1;
}
//构建上边
for (int j = n - 1; j > i + 1; --j)
{
pMatrix[i][j - 1] = pMatrix[i][j] + 1;
}
//构建下一个矩阵的开始
pMatrix[i + 1][i + 1] = pMatrix[i][i + 1] + 1;
--n;
}
if (width % 2 == 0)
{
pMatrix[width / 2][width / 2] = pMatrix[width / 2][width / 2 - 1] + 1;
}
return pMatrix ;
}
//主调函数
int main()
{
printf("请输入矩阵宽度:");
int width = 0;
cin >> width;
printf("输入的数字是:[%d] \n", width);
int **pMatrix = BuildMatrix(width);
for (int i = 0; i < width; ++i)
{
for (int j = 0; j < width; ++j)
{
printf("%d ", pMatrix[i][j]);
}
printf("\n");
}
system("pause");
}