我是靠谱客的博主 清新皮皮虾,最近开发中收集的这篇文章主要介绍《剑指offer》顺时针打印矩阵,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

【 声明:版权所有,转载请标明出处,请勿用于商业用途。  联系信箱:libin493073668@sina.com】


题目链接:http://www.nowcoder.com/practice/9b4c81a02cd34f76be2659fa0d54342a?rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking


题目描述
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵: 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.

思路
首先我们在纸上画出整个打印过程,我们可以知道每次都是走一个圈,而走完这个圈我们需要四个循环,并且要标记好这四个循环每次走的头和尾,那么我们就可以完成整个打印过程了。


class Solution
{
	public:
		vector<int> printMatrix(vector<vector<int> > a)
		{
			vector<int> ans;
			int row = a.size();
			if(row==0)
				return ans;
			int col = a[0].size();
			int start = 0;
			while(col>start*2 && row>start*2)
			{
				int endx = row-1-start,endy = col-1-start;
				int i;

				for(i = start; i<=endy; ++i)
					ans.push_back(a[start][i]);
				if(start<endx)
				{
					for(i = start+1; i<=endx; ++i)
						ans.push_back(a[i][endy]);
				}
				if(start<endx && start<endy)
				{
					for(i = endy-1; i>=start; --i)
						ans.push_back(a[endx][i]);
				}
				if(start<endx-1 && start<endy)
				{
					for(i = endx-1; i>=start+1; --i)
						ans.push_back(a[i][start]);
				}

				++start;
			}
			return ans;
		}
};


最后

以上就是清新皮皮虾为你收集整理的《剑指offer》顺时针打印矩阵的全部内容,希望文章能够帮你解决《剑指offer》顺时针打印矩阵所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(46)

评论列表共有 0 条评论

立即
投稿
返回
顶部