• 输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.


    // test14.cpp : 定义控制台应用程序的入口点。
    //

    #include "stdafx.h"
    #include<iostream>
    #include<string>
    #include<cctype>
    #include <vector>
    #include<exception>
    #include <initializer_list>
    #include<stack>
    using namespace std;
    
    class Solution {
    public:
    	vector<int> printMatrix(vector<vector<int> > matrix) {
    
    		int row1 = 0, row2 = matrix.size();
    		int col1 = 0, col2 = matrix[0].size();
    		vector<int> result;
    		
    		while (true)
    		{
    			//从左到右打印
    			for (int i = col1; i < col2; i++)
    			{
    				result.push_back(matrix[row1][i]);
    		
    			}
    			row1++; 
    			if (row1 >= row2)break; //循环终止条件
    			
    			//从上往下打印
    			for (int i = row1; i < row2; i++)
    			{
    				result.push_back(matrix[i][col2-1]);
    		
    			}
    			col2--; 
    			if (col1 >= col2)break;
    
    			//从右往左打印
    			for (int i = col2-1; i >= col1; i--)
    			{
    				result.push_back(matrix[row2-1][i]);
    			
    			}
    			row2--; 
    			if (row1 >= row2)break;
    
    			//从下往上打印
    			for (int i = row2-1; i >= row1; i--)
    			{
    				result.push_back(matrix[i][col1]);
    			}
    			col1++;
    			if (col1 >= col2)break;
    	
    		}
    		
    		return result;
    	}
    };
    
    int main()
    {
    	
    	Solution so;
    	vector<vector<int>> matrix;
    	vector<int> vec;
    	vector<int> result;
    
    	vec = { 1,2,3,4};
    	matrix.push_back(vec);
    	vec = { 5,6,7,8 };
    	matrix.push_back(vec);
    	vec = { 9,10,11,12 };
    	matrix.push_back(vec);
    	vec = {13,14,15,16 };
    	matrix.push_back(vec);
    	
    	result = so.printMatrix(matrix);
    
    	while (!result.empty())
    	{
    		cout << *(result.end()-1) << "  ";
    		result.pop_back();
    	}
     
    
    	cout << endl;
    	return 0;
    }
  • 相关阅读:
    加了一句话
    由于数据库 'XXX' 离线,无法打开该数据库。
    Linux命令list
    js 数组去重
    JSON.parse(JSON.stringify()) 实现对对象的深度拷贝,从而互不影响
    docker
    Node child_process Study.2
    node assert模块 Study.1
    git 合并本地分支到远程分支
    Vue 项目搭建
  • 原文地址:https://www.cnblogs.com/wdan2016/p/5946158.html
Copyright © 2020-2023  润新知