【算法】回形遍历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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值