如何使用C#在一個行級增加的矩陣中搜索?


解決此問題的原始方案是掃描儲存在輸入矩陣中的所有元素,以搜尋給定的關鍵字。如果矩陣的大小為 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

更新於: 17-Aug-2021

146 次瀏覽

開始您的事業

透過完成課程獲取認證

開始
廣告
© . All rights reserved.