从C ++点开始以螺旋形式打印矩阵
在这个问题上,我们是一个二维矩阵和一个点P(c,r)。我们的任务是从给定点P开始以螺旋形式(逆时针)打印矩阵的所有元素。
让我们举一个例子来了解我们的问题,
Input: matrix[][] = {{3, 5, 7} }Output:
为了解决这个问题,我们使用4个循环来打印元素。每个循环都打印其自身方向的元素。我们将从点p开始打印,然后继续打印螺旋形表格。
示例
显示我们解决方案实施情况的程序
#include <iostream>using namespace std;
const int MAX = 100;
void printSpiralMatrix(int mat[][MAX], int r, int c) {
int i, a = 0, b = 2;
int low_row = (0 > a) ? 0 : a;
int low_column = (0 > b) ? 0 : b - 1;
int high_row = ((a + 1) >= r) ? r - 1 : a + 1;
int high_column = ((b + 1) >= c) ? c - 1 : b + 1;
while ((low_row > 0 - r && low_column > 0 - c)) {
for (i = low_column + 1; i <= high_column && i < c && low_row >= 0; ++i)
cout<<mat[low_row][i]<<" ";
low_row -= 1;
for (i = low_row + 2; i <= high_row && i < r && high_column < c; ++i)
cout<<mat[i][high_column]<<" ";
high_column += 1;
for (i = high_column - 2; i >= low_column && i >= 0 && high_row < r; --i)
cout << mat[high_row][i]<<" ";
high_row += 1;
for (i = high_row - 2; i > low_row && i >= 0 && low_column >= 0; --i)
cout<<mat[i][low_column]<<" ";
low_column -= 1;
}
cout << endl;
}
int main() {
int mat[][MAX] = {
{ 1, 4, 7 },
{ 2, 5, 8 },
{ 3, 6, 9 }
};
int r = 3, c = 3;
cout<<"Sprial traversal of matrix starting from point "<<r<<", "<<c<<" is :\n";
printSpiralMatrix(mat, r, c);
}
输出结果
从点3,3开始的矩阵的遍历为-
7 8 5 4 9 6 3 2 1
以上是 从C ++点开始以螺旋形式打印矩阵 的全部内容, 来源链接: utcz.com/z/354983.html