数据结构与算法中,矩阵是一个重要的概念,它既是数据结构的一种,也是算法中经常需要处理的对象。以下是对矩阵的详细介绍:
矩阵(Matrix)是一个按照长方阵列排列的复数或实数集合,它是一个二维的数据结构,由行和列组成,通常用来表示二维的数据集合。在数学中,矩阵最早来自于方程组的系数及常数所构成的方阵,这一概念由19世纪英国数学家凯利首先提出。在数据结构中,矩阵主要讨论如何在节省存储空间的前提下,正确高效地运算矩阵。
矩阵的运算包括加法、减法、乘法、转置等。
矩阵在计算机科学中有着广泛的应用,比如在机器学习和人工智能领域中,矩阵被用来表示数据集合和模型参数,进行数据处理和计算。在图形学中,矩阵被用来表示图像的像素值和进行图像处理操作。在网络编程中,矩阵也被用来表示网络拓扑结构和进行数据传输。此外,在物理学、工程学、经济学等多个领域,矩阵也有着重要的应用。
题目描述:
给定一个正整数n,生成一个包含1到n^2所有元素,且元素按顺时针顺序螺旋排列的n x n正方形矩阵。
解题思路:
#include using namespace std; vector> generateMatrix(int n) { vector> matrix(n, vector(n, 0)); int num = 1, left = 0, right = n - 1, top = 0, bottom = n - 1; while (num <= n * n) { // Traverse right for (int i = left; i <= right && num <= n * n; ++i) { matrix[top][i] = num++; } top++; // Traverse down for (int i = top; i <= bottom && num <= n * n; ++i) { matrix[i][right] = num++; } right--; // If not the last element if (top <= bottom) { // Traverse left for (int i = right; i >= left && num <= n * n; --i) { matrix[bottom][i] = num++; } bottom--; } if (left <= right) { // Traverse up for (int i = bottom; i >= top && num <= n * n; --i) { matrix[i][left] = num++; } left++; } } return matrix; } 题目描述:
编写一个高效的算法来搜索m x n矩阵matrix中的一个目标值target。该矩阵具有以下特性:每行的元素从左到右升序排列;每列的元素从上到下升序排列。
解题思路:
#include using namespace std; bool searchMatrix(vector>& matrix, int target) { if (matrix.empty() || matrix[0].empty()) return false; int rows = matrix.size(), cols = matrix[0].size(); int row = 0, col = cols - 1; while (row < rows && col >= 0) { if (matrix[row][col] == target) return true; else if (matrix[row][col] < target) row++; else col--; } return false; } 题目描述:
给定一个n x n的二维矩阵matrix表示一个图像。请你将图像顺时针旋转90度。你必须在原地旋转图像,这意味着你需要直接修改输入的二维矩阵。请不要使用另一个矩阵来旋转图像。
解题思路:
#include using namespace std; void rotate(vector>& matrix) { int n = matrix.size(); // Flip along the diagonal for (int i = 0; i < n; ++i) { for (int j = i; j < n; ++j) { swap(matrix[i][j], matrix[j][i]); } } // Flip each row for (int i = 0; i < n; ++i) { for (int j = 0; j < n / 2; ++j