如何使用 C# 在按行按列遞增的矩陣裡搜尋?
解決此問題的基本方法是掃描儲存在輸入矩陣中的所有元素以搜尋給定的鍵。如果矩陣的大小為 MxN,則此線性搜尋方法的代價為 O(MN) 時間。
矩陣可以視為已排序的一維陣列。如果輸入矩陣中的所有行按從上到下的順序連在一起,它將形成已排序的一維陣列。在這種情況下,二分搜尋演算法適用於此 2D 陣列。下面這段程式碼開發了一個函式 SearchRowwiseColumnWiseMatrix,它接受一個二維陣列和搜尋鍵作為輸入,並根據搜尋鍵的查詢成功或失敗返回 true 或 false。
示例
public class Matrix{
public bool SearchRowwiseColumnWiseMatrix(int[,] mat, int searchElement){
int col = getMatrixColSize(mat);
int start = 0;
int last = mat.Length - 1;
while (start <= last){
int mid = start + (last - start) / 2;
int mid_element = mat[mid / col, mid % col];
if (searchElement == mid_element){
return true;
}
else if (searchElement < mid_element){
last = mid - 1;
}
else{
start = mid + 1;
}
}
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, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } };
Console.WriteLine(m.SearchRowwiseColumnWiseMatrix(mat, 11));
}輸出
TRUE
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP