首页 > 解决方案 > 如何找到从中心开始的方阵螺旋遍历的循环不变量

问题描述

我们知道不变量是表达式,在循环之前、每次迭代中和循环之后都是如此。所以我们应该找出下面的方阵螺旋遍历代码的所有不变量,从它的中心开始。

循环探索:

int iInd = N / 2;
int jInd = N / 2;
int iStep = 1;
int jStep = 1;

printf("%d ", A[iInd][jInd]);
for (int i = 0; i < N; i++) {
    for (int h = 0; h < i; h++)
        printf("%d ", A[iInd][jInd += jStep]);
        for (int v = 0; v < i; v++)
            printf("%d ", A[iInd += iStep][jInd]);
        jStep = -jStep;
        iStep = -iStep;
}
for (int h = 0; h < N - 1; h++)
    printf("%d ", A[iInd][jInd += jStep]);

整个C++程序:

#include <stdio.h>
#define N 13

void main() {
    int A[N][N];

    for (int i = 0; i<N; i++)
        for (int j = 0; j<N; j++)
            A[i][j] = i * 13 + j; //simple filling of matrix

    int iInd = N / 2;
    int jInd = N / 2;

    int iStep = 1;
    int jStep = 1;


    printf("%d ", A[iInd][jInd]); //the starting of spiral printing
    for (int i = 0; i < N; i++) {
        for (int h = 0; h < i; h++)
            printf("%d ", A[iInd][jInd += jStep]);
        for (int v = 0; v < i; v++)
            printf("%d ", A[iInd += iStep][jInd]);
        jStep = -jStep;
        iStep = -iStep;
    }
    for (int h = 0; h < N - 1; h++)
        printf("%d ", A[iInd][jInd += jStep]);
    //the ending of spiral printing
}

程序的输出和内部结构: 图片在这里

我向老师展示了我的想法 - 不变量是:

  1. 我 < N+1
  2. h < N
  3. v < N

老师告诉我,它不是不变量。它应该是表达式,包含iIndjInd

标签: invariantsloop-invariant

解决方案


推荐阅读