搜尋
首頁後端開發C++查詢以更新的矩陣中連接的非空單元格的數量

查詢以更新的矩陣中連接的非空單元格的數量

Sep 10, 2023 am 09:01 AM
查詢單元格更新數量連接矩陣非空

查詢以更新的矩陣中連接的非空單元格的數量

矩陣可以被認為是按行和列組織的單元格的集合。每個單元格可以包含一個值,該值可以為空或非空。在電腦程式設計中,矩陣通常用於表示二維網格中的資料。

在本文中,我們將討論如何有效地計算矩陣中連接的非空單元格的數量,同時考慮到矩陣可能的更新。我們將探索解決此問題的不同方法,並提供真實的程式碼範例來演示實作。

文法

使用 C/C 查詢矩陣中連接的非空白單元格數量並進行更新的基本語法可以定義如下 -

int queryCount(int matrix[][MAX_COLS], int rows, int cols);

其中matrix是輸入的“矩陣”,“rows”和“cols”分別表示矩陣中的行數和列數。函數「queryCount」傳回一個整數值,表示矩陣中連接的非空單元格的數量。

演算法

為了解決這個問題,我們可以遵循以下演算法 -

第 1 步 - 將變數「count」初始化為 0,這將儲存連接的非空白單元格的計數。

第 2 步 - 迭代矩陣中的每個單元格。

步驟 3 - 對於每個單元格,檢查它是否非空(即包含非空值)。

第 4 步 - 如果儲存格非空,則將「計數」增加 1。

步驟 5 - 檢查單元格是否有任何非空的相鄰單元格。

第 6 步 - 如果相鄰儲存格非空,則將「計數」增加 1。

步驟 7 - 對所有相鄰儲存格重複步驟 5-6。

第 8 步 - 8:迭代矩陣中的所有單元格後,返回「計數」作為最終結果。

方法

  • 方法 1 - 解決此問題的常見方法是使用深度優先搜尋 (DFS) 演算法

  • #方法 2 - 實作查詢以尋找具有更新的矩陣中連接的非空白單元格計數的另一種方法是使用廣度優先搜尋 (BFS) 演算法。

方法 1

在這種方法中,DFS 演算法涉及遞歸遍歷矩陣並追蹤訪問過的單元以避免重複計數。

範例 1

此方法在二維矩陣上執行深度優先搜尋。矩陣的維數、單元格值和查詢次數都是隨機決定的。 countConnectedCells 子程式執行 DFS 並傳回互連的非空白儲存格的計數,從位於指定行和列的儲存格開始。 updateCell 函數更新矩陣中單元格的值。主函數使用當前時間啟動隨機種子,然後產生隨機矩陣大小和元素,然後是隨機數量的查詢。對於每個查詢,程式碼隨機選擇計數查詢 (1) 或更新查詢 (2) 並執行對應的操作。如果查詢的類型為 1,則呼叫 countConnectedCells 函數來決定互連的非空單元格的計數並列印結果。如果查詢類型為2,則呼叫updateCell函數調整指定單元格的值。

#include <iostream>
using namespace std;

const int MAX_SIZE = 100; // Maximum size of the matrix

// Function to count connected non-empty cells using DFS
int countConnectedCells(int matrix[][MAX_SIZE], int rows, int cols, int row, int col, int visited[][MAX_SIZE]) {
   if (row < 0 || row >= rows || col < 0 || col >= cols || matrix[row][col] == 0 || visited[row][col])
      return 0;

   visited[row][col] = 1;
   int count = 1; // Counting the current cell as non-empty
   count += countConnectedCells(matrix, rows, cols, row - 1, col, visited); // Check top cell
   count += countConnectedCells(matrix, rows, cols, row + 1, col, visited); // Check bottom cell
   count += countConnectedCells(matrix, rows, cols, row, col - 1, visited); // Check left cell
   count += countConnectedCells(matrix, rows, cols, row, col + 1, visited); // Check right cell

   return count;
}

// Function to update a cell in the matrix
void updateCell(int matrix[][MAX_SIZE], int rows, int cols, int row, int col, int newValue) {
   matrix[row][col] = newValue;
}

// Function to initialize the matrix
void initializeMatrix(int matrix[][MAX_SIZE], int rows, int cols) {
   for (int i = 0; i <rows; i++) {
      for (int j = 0; j < cols; j++) {
         cin >> matrix[i][j]; // Taking input for each cell in the matrix
      }
   }
}

int main() {
   int rows, cols; // Input matrix size
   cin >> rows >> cols; // Taking input for matrix size

   int matrix[MAX_SIZE][MAX_SIZE]; // Matrix to store the values
   int visited[MAX_SIZE][MAX_SIZE] = {0}; // Visited matrix to keep track of visited cells

   initializeMatrix(matrix, rows, cols); // Initialize the matrix with input values

   int queries; // Input number of queries
   cin >> queries; // Taking input for number of queries

   for (int i = 0; i < queries; i++) {
      int queryType; // Input query type (1 for count query, 2 for update query)
      cin >> queryType; // Taking input for query type

      if (queryType == 1) {
         int row, col; // Input row and column for count query
         cin >> row >> col; // Taking input for row and column
         int count = countConnectedCells(matrix, rows, cols, row, col, visited); // Call countConnectedCells function
         cout << "Count of connected non-empty cells at (" << row << ", " << col << "): " << count << endl; // Print result
      } else if (queryType == 2) {
         int row, col, newValue; // Input row, column, and new value for update query
         cin >> row >> col >> newValue; // Taking input for row, column, and new value
         updateCell(matrix, rows, cols, row, col, newValue); // Call updateCell function
      }
   }
   return 0;
}

輸出

Count of connected non-empty cells at (1, 2): 0
Count of connected non-empty cells at (0, 1): 2

方法2

在這個方法中,廣度優先搜尋(BFS)是另一種圖遍歷演算法,可用於尋找矩陣中連接的非空白單元格的數量。在 BFS 中,我們從給定的單元開始,以廣度優先的方式(即逐層)探索其所有相鄰單元。我們使用佇列來追蹤要存取的儲存格,並標記已存取的儲存格以避免多次計數。

範例 2

此程式碼構成了一個在二維矩陣上執行廣度優先搜尋演算法的軟體。矩陣的維數、單元格值和查詢數量是任意產生的。此程式碼包含兩個子程式:一個用於執行 BFS,另一個用於調整矩陣內的單元。

BFS 作業從隨機選擇的小區開始,並檢查其相鄰小區以確定它們是否互連且未被佔用。如果是這樣,它們將被附加到隊列中並以類似的方式處理。更新矩陣內的單元僅涉及更改其值。產生矩陣和查詢數量後,程式碼隨機選擇 BFS 查詢或更新查詢並執行適當的操作。 BFS 查詢的結果是從所選單元格開始的互連未佔用單元格的計數。

程式碼

#include <iostream>
#include <queue>
#include <ctime>
#include <cstdlib>

using namespace std;

const int MAX_SIZE = 100;

// Function to perform Breadth-First Search (BFS)
int bfs(int matrix[][MAX_SIZE], int rows, int cols, int row, int col, int visited[][MAX_SIZE]) {
   int count = 0;
   queue<pair<int, int>> q;
   q.push({row, col});

   while (!q.empty()) {
      pair<int, int> currentCell = q.front();
      q.pop();

      int currentRow = currentCell.first;
      int currentCol = currentCell.second;

      if (currentRow >= 0 && currentRow <rows && currentCol >= 0 && currentCol < cols && !visited[currentRow][currentCol] && matrix[currentRow][currentCol] == 1) {
         count++;
         visited[currentRow][currentCol] = 1;

         q.push({currentRow - 1, currentCol});
         q.push({currentRow + 1, currentCol});
         q.push({currentRow, currentCol - 1});
         q.push({currentRow, currentCol + 1});
      }
   }
   return count;
}
// Function to update a cell in the matrix
void updateCell(int matrix[][MAX_SIZE], int row, int col, int newValue) {
   matrix[row][col] = newValue;
}

// Function to generate a random integer between min and max (inclusive)
int randomInt(int min, int max) {
   return rand() % (max - min + 1) + min;
}

int main() {
   srand(time(0));

   int rows = randomInt(1, 10);
   int cols = randomInt(1, 10);

   int matrix[MAX_SIZE][MAX_SIZE];
   int visited[MAX_SIZE][MAX_SIZE] = {0};

   for (int i = 0; i < rows; i++) {
      for (int j = 0; j < cols; j++) {
         matrix[i][j] = randomInt(0, 1);
      }
   }

   int queries = randomInt(1, 5);

   for (int i = 0; i < queries; i++) {
      int queryType = randomInt(1, 2);

      if (queryType == 1) {
         int row = randomInt(0, rows - 1);
         int col = randomInt(0, cols - 1);
         int count = bfs(matrix, rows, cols, row, col, visited);
         cout << "Count of connected non-empty cells at (" << row << ", " << col << "): " << count << endl;
      } else if (queryType == 2) {
         int row = randomInt(0, rows - 1);
         int col = randomInt(0, cols - 1);
         int newValue = randomInt(0, 1);
         updateCell(matrix, row, col, newValue);
      }
   }
   return 0;
}

輸出

Count of connected non-empty cells at (0, 0): 0

結論

在本文中,我們討論了兩種使用 C/C 尋找矩陣中連接的非空白單元格數量並進行更新的方法。深度優先搜尋(DFS)演算法和並集查找(不相交集並集)。在為特定用例選擇最合適的方法之前,分析每種方法的時間複雜度和空間複雜度非常重要。

以上是查詢以更新的矩陣中連接的非空單元格的數量的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文轉載於:tutorialspoint。如有侵權,請聯絡admin@php.cn刪除
C:死亡還是簡單地發展?C:死亡還是簡單地發展?Apr 24, 2025 am 12:13 AM

1)c relevantduetoItsAverity and效率和效果臨界。 2)theLanguageIsconTinuellyUped,withc 20introducingFeaturesFeaturesLikeTuresLikeSlikeModeLeslikeMeSandIntIneStoImproutiMimproutimprouteverusabilityandperformance.3)

C在現代世界中:應用和行業C在現代世界中:應用和行業Apr 23, 2025 am 12:10 AM

C 在現代世界中的應用廣泛且重要。 1)在遊戲開發中,C 因其高性能和多態性被廣泛使用,如UnrealEngine和Unity。 2)在金融交易系統中,C 的低延遲和高吞吐量使其成為首選,適用於高頻交易和實時數據分析。

C XML庫:比較和對比選項C XML庫:比較和對比選項Apr 22, 2025 am 12:05 AM

C 中有四種常用的XML庫:TinyXML-2、PugiXML、Xerces-C 和RapidXML。 1.TinyXML-2適合資源有限的環境,輕量但功能有限。 2.PugiXML快速且支持XPath查詢,適用於復雜XML結構。 3.Xerces-C 功能強大,支持DOM和SAX解析,適用於復雜處理。 4.RapidXML專注於性能,解析速度極快,但不支持XPath查詢。

C和XML:探索關係和支持C和XML:探索關係和支持Apr 21, 2025 am 12:02 AM

C 通過第三方庫(如TinyXML、Pugixml、Xerces-C )與XML交互。 1)使用庫解析XML文件,將其轉換為C 可處理的數據結構。 2)生成XML時,將C 數據結構轉換為XML格式。 3)在實際應用中,XML常用於配置文件和數據交換,提升開發效率。

C#vs. C:了解關鍵差異和相似之處C#vs. C:了解關鍵差異和相似之處Apr 20, 2025 am 12:03 AM

C#和C 的主要區別在於語法、性能和應用場景。 1)C#語法更簡潔,支持垃圾回收,適用於.NET框架開發。 2)C 性能更高,需手動管理內存,常用於系統編程和遊戲開發。

C#與C:歷史,進化和未來前景C#與C:歷史,進化和未來前景Apr 19, 2025 am 12:07 AM

C#和C 的歷史與演變各有特色,未來前景也不同。 1.C 由BjarneStroustrup在1983年發明,旨在將面向對象編程引入C語言,其演變歷程包括多次標準化,如C 11引入auto關鍵字和lambda表達式,C 20引入概念和協程,未來將專注於性能和系統級編程。 2.C#由微軟在2000年發布,結合C 和Java的優點,其演變注重簡潔性和生產力,如C#2.0引入泛型,C#5.0引入異步編程,未來將專注於開發者的生產力和雲計算。

C#vs. C:學習曲線和開發人員的經驗C#vs. C:學習曲線和開發人員的經驗Apr 18, 2025 am 12:13 AM

C#和C 的学习曲线和开发者体验有显著差异。1)C#的学习曲线较平缓,适合快速开发和企业级应用。2)C 的学习曲线较陡峭,适用于高性能和低级控制的场景。

C#vs. C:面向對象的編程和功能C#vs. C:面向對象的編程和功能Apr 17, 2025 am 12:02 AM

C#和C 在面向对象编程(OOP)中的实现方式和特性上有显著差异。1)C#的类定义和语法更为简洁,支持如LINQ等高级特性。2)C 提供更细粒度的控制,适用于系统编程和高性能需求。两者各有优势,选择应基于具体应用场景。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。