码迷,mamicode.com
首页 > 其他好文 > 详细

Rotate Image --LeetCode

时间:2015-04-07 19:43:35      阅读:102      评论:0      收藏:0      [点我收藏+]

标签:c++   leetcode   算法   

题目:

You are given an n x n 2D matrix representing an image.

Rotate the image by 90 degrees (clockwise).

Follow up:
Could you do this in-place?

思路:使用最基本的方法,递归,但是有空间复杂度

#include <iostream> 
#include <vector>
#include <string>
using namespace std;


void helper(vector<vector<int> >& vec,int n)
{
	if(n == vec.size() || n+1 == vec.size())
		return ;
	int i = n/2,j = (vec.size()-1)-n/2; //i表示行 j表示列 
	vector<int> tmp(vec[i].begin()+i,vec[i].begin()+j+1);
	
	int k,m;

	for(k=i,m=j;k<=j;k++,m--)
		vec[i][m]= vec[k][i];
	for(k=i;k<=j;k++)
		vec[k][i] = vec[j][k];
	for(k=i,m=j;k<=j;k++,m--)
		vec[j][k] = vec[m][j];
	for(k=i,m=0;k<=j;k++,m++)
		vec[k][j] = tmp[m];
	helper(vec,n+2);
}
void RotateImage(vector<vector<int> >& vec)
{
	if(vec.size()<=1)
		return ;
	helper(vec,0);
}

int main()
{
	vector<int> vec(6,0);
	vector<vector<int> > image;
	int i,j;

	for(i=0;i<vec.size();i++)
	{
		for(j=0;j<vec.size();j++)
			vec[j] = i+j+1;
		image.push_back(vec); 
	}
	
	for(i=0;i<vec.size();i++)
	{
		for(j=0;j<vec.size();j++)
			cout<<image[i][j]<<" ";
		cout<<endl;
	}
	
	RotateImage(image);
	cout<<"========="<<endl;
	for(i=0;i<vec.size();i++)
	{
		for(j=0;j<vec.size();j++)
			cout<<image[i][j]<<" ";
		cout<<endl;
	}
	return 0;	
}


Rotate Image --LeetCode

标签:c++   leetcode   算法   

原文地址:http://blog.csdn.net/yusiguyuan/article/details/44924409

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!