如何使用 C# 在逐行递增的矩阵中进行搜索?
csharpserver side programmingprogramming更新于 2025/6/28 4:52:17
此问题的基本解决方案是扫描输入矩阵中存储的所有元素以搜索给定的键。如果矩阵大小为 MxN,则此线性搜索方法的时间为 O(MN)。
需要从右上方开始扫描矩阵,如果搜索元素大于右上方元素,则增加行数,否则减少列数。以下代码开发了一个 SearchRowwiseIncrementedMatrix 函数,该函数以二维数组和搜索键作为输入,并根据搜索键是否成功返回 true 或 false。
代码
public class Matrix{
public bool SearchRowwiseIncrementedMatrix(int[,] mat, int searchElement){
int row = getMatrixRowSize(mat);
int col = getMatrixColSize(mat) - 1;
int r = 0;
while (col >= 0 && r < row){
if (mat[r, col] == searchElement){
return true;
}
else if (searchElement < mat[r, col]){
col--;
}
else{
r++;
}
}
return false;
}
private int getMatrixRowSize(int[,] mat){
return mat.GetLength(0);
}
private int getMatrixColSize(int[,] mat){
return mat.GetLength(1);
}
}
static void Main(string[] args){
Matrix m = new Matrix();
int[,] mat = new int[3, 4] { { 1, 7, 10, 19 }, { 2, 8, 11, 20 }, { 3, 9, 12, 21 } };
Console.WriteLine(m.SearchRowwiseIncrementedMatrix(mat, 11));
}
输出
TRUE

