作文以记之~旋转图像

作文以记之~旋转图像,第1张

作文以记之~旋转图像
  • 0、前言
  • 1、问题描述
  • 2、解题思路
    • 2.1 原地旋转
      • 2.1.1 思路
      • 2.1.2 程序代码
      • 2.1.3 运行结果
    • 2.2 利用翻转
      • 2.2.1 思路
      • 2.2.2 程序代码
      • 2.2.3 运行结果

0、前言

本篇博客将记录一下作者自己做题时的一些题解或思路,写的不详细。


相关题目可 点击此处 进行查看!具体代码以及其他内容可 点击此处 进行查看!

1、问题描述

该题虽然题目是旋转图像,但实际上是旋转矩阵,即将矩阵旋转90度!

2、解题思路 2.1 原地旋转 2.1.1 思路

这个题要求不能用另一个数组去进行旋转,所以就需考虑其他方法。


方法之一就是通过旋转前后,找出矩阵元素旋转前后的位置规律,然后将其代码化,再确定作用范围进行遍历即可。


如图

此种方法官方题解中也有具体说明,有需要者可 点击此处 进行查看!

2.1.2 程序代码
#include
#include
using namespace std;

void showmatrix(vector<vector<int>>& matrix)
{
	for (int i = 0; i < matrix.size(); i++)
	{
		for (int j = 0; j < matrix[0].size(); j++)
		{
			cout << matrix[i][j] << " ";
		}
		cout << endl;
	}
	cout << endl;
}

void rotate(vector<vector<int>>& matrix) {
	int n = matrix.size();
	for (int i = 0; i<(n / 2); i++)
	{
		//for(int j = 0;j<(n+1)/2;j++)
		for (int j = i; j<(n - 1 - i); j++)
		{
			int tmp = matrix[i][j];
			matrix[i][j] = matrix[n - 1 - j][i];
			matrix[n - 1 - j][i] = matrix[n - 1 - i][n - j - 1];
			matrix[n - 1 - i][n - 1 - j] = matrix[j][n - i - 1];
			matrix[j][n - i - 1] = tmp;
		}
	}
}

void test()
{
	// 定义数独
	vector<vector<int>> matrix = {
		{5, 1, 9, 11}, 
		{2, 4, 8, 10}, 
		{13, 3, 6, 7}, 
		{15, 14, 12, 16} };

	cout << "\n翻转前:" << endl;
	showmatrix(matrix);
	cout << "\n翻转后:" << endl;
	rotate(matrix);
	showmatrix(matrix);
	cout << endl;
}

int main()
{
	test();
	system("pause");
	return 0;
}
2.1.3 运行结果

2.2 利用翻转 2.2.1 思路

这个思路主要是先将数组上下交换,然后再按右对角线进行交换,便可实现矩阵的翻转!如图

2.2.2 程序代码
#include
#include
using namespace std;

void showmatrix(vector<vector<int>>& matrix)
{
	for (int i = 0; i < matrix.size(); i++)
	{
		for (int j = 0; j < matrix[0].size(); j++)
		{
			cout << matrix[i][j] << " ";
		}
		cout << endl;
	}
	cout << endl;
}

/* 方法2:先上下交换,再按右斜对角线交换*/
void rotate(vector<vector<int>>& matrix) {
	int n = matrix.size();
	//先上下交换
	for (int i = 0; i < (n / 2); i++)
		swap(matrix[i], matrix[n-1 - i]);
	//按右斜对角线交换
	for (int i = 0; i < n; i++)
		for (int j = i; j < n; j++)
			swap(matrix[i][j], matrix[j][i]);
}

void test()
{
	// 定义数独
	vector<vector<int>> matrix = {
		{5, 1, 9, 11}, 
		{2, 4, 8, 10}, 
		{13, 3, 6, 7}, 
		{15, 14, 12, 16} };

	cout << "\n翻转前:" << endl;
	showmatrix(matrix);
	cout << "\n翻转后:" << endl;
	rotate(matrix);
	showmatrix(matrix);
	cout << endl;
}

int main()
{
	test();
	system("pause");
	return 0;
}
2.2.3 运行结果

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/563415.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-02
下一篇 2022-04-02

发表评论

登录后才能评论

评论列表(0条)

保存