顺时针打印数组

10 篇文章 1 订阅

顺时针打印数组

思路

  • 依次按照四个方向遍历一次,如果计数值到达数组个数,则退出,无需考虑其他的停止条件。

代码

#include <cstdlib>
#include <string>
#include <iostream>
#include <fstream>
#include <vector>
#include <sstream>
#include <unordered_map>
#include <unordered_set>
#include <map>
#include <set>
#include <stdio.h>
#include <numeric>
#include <algorithm>
#include <functional>
#include <stack>
#include <queue>

using namespace std;
typedef long long ll;
const int MOD = 1e9 + 7;
typedef unsigned char uchar;

int dirs[8][2] = { -1, -1, -1, 0, -1, 1, 0, -1, 0, 1, 1, -1, 1, 0, 1, 1 };

#define MAX_DIST 1e9

int main(int /*argc*/, char** /*argv*/)
{
    int rows = 5, cols = 3;
    vector<vector<int>> nums( rows, vector<int>(cols,0) );
    for (int i = 0; i < rows; ++i)
    {
        for (int j = 0; j < cols; ++j)
        {
            nums[i][j] = j + i*cols;
            printf("%d ", nums[i][j]);
        }
        printf("\n");
    }   

    int sum_num = rows * cols;
    int start_row = 0, end_row = rows - 1, start_col = 0, end_col = cols - 1;
    int cnt = 0;
    int curr_row = 0, curr_col = 0;
    while ( true )
    {
        // 向右遍历
        for (int i = start_col; i <= end_col; ++i)
        {
            printf("%d,", nums[start_row][i]);
            ++cnt;
        }
        if (cnt >= sum_num)
            break;
        ++start_row;

        // 向下遍历
        for (int i = start_row; i <= end_row; ++i)
        {
            printf("%d,", nums[i][end_col]);
            ++cnt;
        }
        if (cnt >= sum_num)
            break;
        --end_col;

        // 向左遍历
        for (int i = end_col; i >= start_col; i--)
        {
            printf("%d,", nums[end_row][i]);
            ++cnt;
        }
        if (cnt >= sum_num)
            break;
        --end_row;

        // 向上遍历
        for (int i = end_row; i >= start_row; --i)
        {
            printf("%d,", nums[i][start_col]);
            ++cnt;
        }

        if (cnt >= sum_num)
            break;
        ++start_col;

    }

    system("pause");
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

littletomatodonkey

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值