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

剑指offer: 输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵: 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. 思路:这个题考虑的情况比较多,考察的是细心程度和面对复杂问题的逻辑分析能力。耐心分析就好。 首先在while里将矩阵输出到只剩下一行或者一列或者一个元素。

		int left = 0 ,right = matrix[0].size()-1,top = 0,bottom = matrix.size()-1;
		vector<int> result;
		while(left < right && top < bottom ){
			for(int i = left; i <= right; i++){//从左到右
				result.push_back(matrix[top][i]);
			}
			for(int i = top  +1; i <= bottom; i++){//从上到下
				result.push_back(matrix[i][right]);
			}
			for(int i = right - 1; i >= left; i--){//从右到左
				result.push_back(matrix[bottom][i]);
			}
			for(int i = bottom - 1; i >= top + 1; i--){//从下到上
				result.push_back(matrix[i][left]);
			}
			left++;
			right--;
			top++;
			bottom--;
		}

然后考虑一行,一列和一个元素的情况,考虑三者之间的重合部分

		if(left <= right && top <= bottom){
			if(left < right){
			   for(int i = left; i <= right; i++){//                
			       result.push_back(matrix[top][i]);
			   }
		    }
		   else if(top < bottom){
			   for(int i = top; i <= bottom; i++){//从上到下
				   result.push_back(matrix[i][right]);
			   }		
		  }
		   else if(left == right && top == bottom){
		       result.push_back(matrix[top][left]);
		   }
		}
		
// JianZhiOffer.cpp : 定义控制台应用程序的入口点。
//

//#include "stdafx.h"
#include <iostream>
#include "stdlib.h"
#include <vector>

using namespace std;
class Solution {
public:
    vector<int> printMatrix(vector<vector<int> > matrix) {
		int left = 0 ,right = matrix[0].size()-1,top = 0,bottom = matrix.size()-1;
		vector<int> result;
		while(left < right && top < bottom ){
			for(int i = left; i <= right; i++){//从左到右
				result.push_back(matrix[top][i]);
			}
			for(int i = top  +1; i <= bottom; i++){//从上到下
				result.push_back(matrix[i][right]);
			}
			for(int i = right - 1; i >= left; i--){//从右到左
				result.push_back(matrix[bottom][i]);
			}
			for(int i = bottom - 1; i >= top + 1; i--){//从下到上
				result.push_back(matrix[i][left]);
			}
			left++;
			right--;
			top++;
			bottom--;
		}
		if(left <= right && top <= bottom){
			if(left < right){
			   for(int i = left; i <= right; i++){//                
			       result.push_back(matrix[top][i]);
			   }
		    }
		   else if(top < bottom){
			   for(int i = top; i <= bottom; i++){//从上到下
				   result.push_back(matrix[i][right]);
			   }		
		  }
		   else if(left == right && top == bottom){
		       result.push_back(matrix[top][left]);
		   }
		}
		
    	return result;
    }
};
int main()
{
	vector<vector<int> > m;
	int num = 0;
	for(int i = 0; i < 3 ; i++ ){
	   vector<int> temp;
	   for(int j = 0; j < 4; j++ ){
		  	temp.push_back(++num);
		}
	   m.push_back(temp);
	}
		
    Solution s;
	s.printMatrix(m);
	cout << "succed" << endl;
	system("pause");
	return 0;
}

    原文作者:杜甫如诗
    原文地址: https://blog.csdn.net/u013686654/article/details/74456113
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞