วิธีแก้ปัญหาเบื้องต้นสำหรับปัญหานี้คือการสแกนองค์ประกอบทั้งหมดที่จัดเก็บไว้ในเมทริกซ์อินพุตเพื่อค้นหาคีย์ที่ระบุ วิธีค้นหาเชิงเส้นนี้ใช้เวลา O(MN) หากขนาดของเมทริกซ์คือ MxN
ต้องสแกนเมทริกซ์จากมุมขวาบน หากองค์ประกอบการค้นหามากกว่าองค์ประกอบด้านขวาบน ให้เพิ่มแถวหรือลดคอลัมน์ โค้ดด้านล่างพัฒนาฟังก์ชัน 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