矩阵的遍历--按行、按列、蛇形

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/i_chaoren/article/details/79237165

这里有一个假设: 

在图像处理等领域中,二维矩阵已经按照行的方式存放在了一维数组mat中了。 

矩阵的高记为height,宽记为width; 

1.按行遍历

for (int i = 0; i < height; ++i)
       for (int j = 0; j < width; ++j)
              mat[i*width + j];
2.按列遍历
仅需调换一下两个for语句的顺序。 

for (int j = 0; j < width; ++j)
       for (int i = 0; i < height; ++i)
              mat[i*width + j];
3.蛇形遍历
蛇形遍历只适合于正方形的矩阵,边长记为n。

基本思想是:让横纵坐标同时变化,就会按照蛇形进行遍历。 

for (int k = 0; k < n; ++k)
       for (int i = k, j = 0; i >= 0; --i, ++j)
              mat[i*n + j];
下面是一段完整的蛇形遍历的代码: 

实现的功能是:生成一个蛇形的矩阵,并且将该矩阵输出。 

#include<iostream>
using namespace std;
int main()
{
       int n;
       while (cin >> n)
       {
              int count = 1;
              int* array = new int[n*n]();
              //生成蛇形矩阵
              for (int k = 0; k < n; ++k)
                     for (int i = k, j = 0; i >= 0; --i, ++j)
                     {
                           array[i*n + j] = count;
                           count++;
                     }
              //输出矩阵
              for (int i = 0; i < n; ++i)
              {
                     for (int j = 0; j < n; ++j)
                           if (array[i*n + j])
                                  if (array[i*n + j + 1] && j < n - 1)
                                         cout << array[i*n + j] << ' ';
                                  else
                                         cout << array[i*n + j];
                     cout << endl;
              }
       }
}
输入5:
输出:
1 3 6 10 15
2 5 9 14
4 8 13
7 12
11


猜你喜欢

转载自blog.csdn.net/i_chaoren/article/details/79237165