【算法】回形遍历N*N的二维数组

题目

通常,可以按照逐行、逐列等不同方法输出二维数组中的全部元素。 如果按照回形的路线(如下图)输出数组中的全部元素,你能给出比较有效的解法吗?

第一行为正整数N(1≤N≤10) 之后有N行、N列个正整数(即N×N二维整型数组中的全部元素)

按回形路线遍历输出N×N二维整型数组中的全部元素,输出时每个元素占1行。

思路

总共有上下左右四个方向的遍历,定义一个变量direction由于记录当前遍历的方向,采用分支结构,每次遍历前先对direction进行判定,遍历完当前这条后,使遍历范围-1,从而实现不断向回形内圈访问。

代码

#include <stdio.h>
int main()
{
    int N;
    scanf("%d", &N);
    int arr[N][N];
    for (int i = 0; i < N; ++i)
    {
        for (int j = 0; j < N; ++j)
        {
            scanf("%d", &arr[i][j]);
        }
    }
    int top = 0, bottom = N - 1, left = 0, right = N - 1;
    int direction = 0;
    while (top <= bottom && left <= right)
    {
        if (direction == 0)
        {
            // Traverse top row
            for (int i = left; i <= right; ++i)
                printf("%d\n", arr[top][i]);
            top++;
        }
        else if (direction == 1)
        {
            // Traverse rightmost column
            for (int i = top; i <= bottom; ++i)
                printf("%d\n", arr[i][right]);
            right--;
        }
        else if (direction == 2)
        {
            // Traverse bottom row
            for (int i = right; i >= left; --i)
                printf("%d\n", arr[bottom][i]);
            bottom--;
        }
        else if (direction == 3)
        {
            // Traverse leftmost column
            for (int i = bottom; i >= top; --i)
                printf("%d\n", arr[i][left]);
            left++;
        }
        direction = (direction + 1) % 4;
    }
    return 0;
}

相关推荐

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-06 07:54:01       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-06 07:54:01       106 阅读
  3. 在Django里面运行非项目文件

    2024-04-06 07:54:01       87 阅读
  4. Python语言-面向对象

    2024-04-06 07:54:01       96 阅读

热门阅读

  1. Git入门实战教程之合并分支并解决冲突

    2024-04-06 07:54:01       36 阅读
  2. 服务器硬件基础知识

    2024-04-06 07:54:01       38 阅读
  3. 设计模式(20):责任链模式

    2024-04-06 07:54:01       35 阅读
  4. 使用Ajax的优点

    2024-04-06 07:54:01       34 阅读
  5. vue基本写法

    2024-04-06 07:54:01       38 阅读
  6. 机器翻译

    2024-04-06 07:54:01       36 阅读
  7. 自然语言处理——计算编辑距离

    2024-04-06 07:54:01       38 阅读