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

来源:互联网 发布:php医院预约挂号源码 编辑:程序博客网 时间:2024/06/06 12:02
剑指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;}



阅读全文
0 0
原创粉丝点击