三角螺旋阵

方阵的主对角线之上称为“上三角”。
请你设计一个用于填充n阶方阵的上三角区域的程序。填充的规则是:使用1,2,3….的自然数列,从左上角开始,按照顺时针方向螺旋填充。
例如:当n=3时,输出:
1 2 3
6 4
5
当n=4时,输出:
1 2 3 4
9 10 5
8 6
7
当n=5时,输出:
1 2 3 4 5
12 13 14 6
11 15 7
10 8
9
程序运行时,要求用户输入整数n(3~20)
程序输出:方阵的上三角部分。
要求格式:每个数据宽度为4,右对齐。

//
//  s_20.cpp
//  swordOffer
//
//  Created by YangKi on 2017/2/14.
//  Copyright © 2017年 yangqi916. All rights reserved.
//

#include <iostream>
#include <vector>
#include <stack>

using namespace std;

class Solution {
    
private:
    vector<int>res;
    int currentDirection = 0;
    int rowIncre[3] = {0, 1, -1};
    int colIncre[3] = {1, -1, 0};
    int rows = 0;
    int cols = 0;
    bool isValid(int row, int col, int n) {
        if((row >= 0 && row < n) && (col >= 0 && col < n-row) )
            return true;
        return false;
    }
    
public:
    
    vector<int> printMatrix(vector<vector<int> > matrix, int n) {
        rows = (int)matrix.size();
        if (rows == 0)
            return res;
        cols = (int)(matrix[0].size());
        if(cols == 0)
            return res;
        
        vector<vector<bool>>isVisited(rows ,vector<bool>(cols, false));
        
        int curRow = 0;
        int curCol = 0;
        int cnt = 0;
        
        int maxnodes = (n*(n+1)) / 2;
        
        while (cnt < maxnodes) {
            cnt++;
            isVisited[curRow][curCol] = true;
            res.push_back(matrix[curRow][curCol]);
            
            if (!isValid(curRow + rowIncre[currentDirection], curCol + colIncre[currentDirection], n)
                || isVisited[curRow + rowIncre[currentDirection]][curCol + colIncre[currentDirection]] == true) {
                // 沿着原来的方向取下一个位置是非法的,需要换方向
                currentDirection = (currentDirection + 1) % 3;
            }
            
            //取下一个位置
            curRow += rowIncre[currentDirection];
            curCol += colIncre[currentDirection];
        }
        
        return res;
    }
};

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,662评论 19 139
  • 一、实验目的 学习使用 weka 中的常用分类器,完成数据分类任务。 二、实验内容 了解 weka 中 explo...
    yigoh阅读 12,768评论 5 4
  • 其实我们都知道,感动不是喜欢。假如你从一开始就不喜欢这个人,那你不会因为他对你的好,而喜欢上他,感动不是喜欢...
    让爱情晚一点回家阅读 5,796评论 2 0
  • VC6虽然老,但是一些工程还非得用它打开,没办法……今天偶然用到,因为新装了系统,之前的问题又要重新解决一遍在这记...
    leftshine阅读 8,311评论 1 4
  • 老陈是我在台球厅认识的,当时的我刚刚来到这个城市,拿着我用十二年的时光换来的一纸文凭,幻想着大城市的灯红酒绿...
    双鱼依泽瑞尔阅读 5,060评论 3 1