Table of Contents
grammar
algorithm
method 1
Example 2
Output
Method 2
Code
in conclusion
Home Backend Development C++ Query to update the number of connected non-empty cells in a matrix

Query to update the number of connected non-empty cells in a matrix

Sep 10, 2023 am 09:01 AM
Inquire Cell renew quantity connect matrix non empty

Query to update the number of connected non-empty cells in a matrix

A matrix can be thought of as a collection of cells organized in rows and columns. Each cell can contain a value, which can be empty or non-empty. In computer programming, matrices are often used to represent data in a two-dimensional grid.

In this article, we will discuss how to efficiently count the number of connected non-empty cells in a matrix, taking into account possible updates to the matrix. We'll explore different ways to solve this problem and provide real-world code examples to demonstrate implementation.

grammar

The basic syntax for querying the number of connected non-empty cells in a matrix and updating it using C/C can be defined as follows -

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

Where matrix is ​​the input "matrix", "rows" and "cols" represent the number of rows and columns in the matrix respectively. The function "queryCount" returns an integer value representing the number of connected non-empty cells in the matrix.

algorithm

To solve this problem, we can follow the following algorithm -

Step 1 - Initialize the variable "count" to 0, this will store the count of connected non-empty cells.

Step 2 - Iterate over each cell in the matrix.

Step 3 - For each cell, check whether it is non-empty (i.e. contains a non-null value).

Step 4 - If the cell is not empty, increase the Count by 1.

Step 5 - Check if the cell has any non-empty adjacent cells.

Step 6 - If the adjacent cell is not empty, increase the Count by 1.

Step 7 - Repeat steps 5-6 for all adjacent cells.

Step 8 - 8: After iterating through all cells in the matrix, return "count" as the final result.

method

  • Method 1 - A common way to solve this problem is to use the Depth First Search (DFS) algorithm

  • Method 2 - Another way to implement a query to find the count of non-empty cells with joins in an updated matrix is ​​to use the Breadth-First Search (BFS) algorithm.

method 1

In this approach, the DFS algorithm involves recursively traversing the matrix and keeping track of visited cells to avoid double counting.

Example 1

This method performs a depth-first search on a two-dimensional matrix. The dimensions, cell values, and number of queries of the matrix are randomly determined. The countConnectedCells subroutine performs DFS and returns a count of connected, non-empty cells, starting with the cell at the specified row and column. The updateCell function updates the value of a cell in a matrix. The main function starts a random seed using the current time, then generates a random matrix size and elements, followed by a random number of queries. For each query, the code randomly selects a count query (1) or an update query (2) and performs the appropriate action. If the query's type is 1, the countConnectedCells function is called to determine the count of connected, non-empty cells and prints the result. If the query type is 2, call the updateCell function to adjust the value of the specified cell.

#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;
}
Copy after login

Output

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

Method 2

In this approach, Breadth First Search (BFS) is another graph traversal algorithm that can be used to find the number of connected non-empty cells in a matrix. In BFS, we start from a given cell and explore all its neighboring cells in a breadth-first manner (i.e., layer-by-layer). We use a queue to keep track of which cells are being accessed, and mark cells that have been accessed to avoid multiple counts.

Example 2

This code constitutes a software that performs a breadth-first search algorithm on a two-dimensional matrix. The dimensions of the matrix, cell values, and number of queries are generated arbitrarily. The code contains two subroutines: one to perform BFS and another to adjust the cells within the matrix.

BFS operation starts with a randomly selected cell and checks its neighboring cells to determine if they are interconnected and unoccupied. If so, they will be appended to the queue and processed in a similar manner. Updating a cell within a matrix only involves changing its value. After generating the matrix and query number, the code randomly selects a BFS query or an update query and performs the appropriate operation. The result of the BFS query is a count of interconnected unoccupied cells starting from the selected cell.

Code

#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;
}
Copy after login

Output

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

in conclusion

In this article, we discussed two methods of using C/C to find the number of connected non-empty cells in a matrix and update them. Depth First Search (DFS) algorithm and union search (union of disjoint sets). It is important to analyze the time complexity and space complexity of each method before choosing the most appropriate method for a specific use case.

The above is the detailed content of Query to update the number of connected non-empty cells in a matrix. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to fix Blizzard Battle.net update stuck at 45%? How to fix Blizzard Battle.net update stuck at 45%? Mar 16, 2024 pm 06:52 PM

Blizzard Battle.net update keeps stuck at 45%, how to solve it? Recently, many people have been stuck at the 45% progress bar when updating software. They will still get stuck after restarting multiple times. So how to solve this situation? We can reinstall the client, switch regions, and delete files. To deal with it, this software tutorial will share the operation steps, hoping to help more people. Blizzard Battle.net update keeps stuck at 45%, how to solve it? 1. Client 1. First, you need to confirm that your client is the official version downloaded from the official website. 2. If not, users can enter the Asian server website to download. 3. After entering, click Download in the upper right corner. Note: Be sure not to select Simplified Chinese when installing.

12306 How to check historical ticket purchase records How to check historical ticket purchase records 12306 How to check historical ticket purchase records How to check historical ticket purchase records Mar 28, 2024 pm 03:11 PM

Download the latest version of 12306 ticket booking app. It is a travel ticket purchasing software that everyone is very satisfied with. It is very convenient to go wherever you want. There are many ticket sources provided in the software. You only need to pass real-name authentication to purchase tickets online. All users You can easily buy travel tickets and air tickets and enjoy different discounts. You can also start booking reservations in advance to grab tickets. You can book hotels or special car transfers. With it, you can go where you want to go and buy tickets with one click. Traveling is simpler and more convenient, making everyone's travel experience more comfortable. Now the editor details it online Provides 12306 users with a way to view historical ticket purchase records. 1. Open Railway 12306, click My in the lower right corner, and click My Order 2. Click Paid on the order page. 3. On the paid page

How to install Angular on Ubuntu 24.04 How to install Angular on Ubuntu 24.04 Mar 23, 2024 pm 12:20 PM

Angular.js is a freely accessible JavaScript platform for creating dynamic applications. It allows you to express various aspects of your application quickly and clearly by extending the syntax of HTML as a template language. Angular.js provides a range of tools to help you write, update and test your code. Additionally, it provides many features such as routing and form management. This guide will discuss how to install Angular on Ubuntu24. First, you need to install Node.js. Node.js is a JavaScript running environment based on the ChromeV8 engine that allows you to run JavaScript code on the server side. To be in Ub

How to check your academic qualifications on Xuexin.com How to check your academic qualifications on Xuexin.com Mar 28, 2024 pm 04:31 PM

How to check my academic qualifications on Xuexin.com? You can check your academic qualifications on Xuexin.com, but many users don’t know how to check their academic qualifications on Xuexin.com. Next, the editor brings you a graphic tutorial on how to check your academic qualifications on Xuexin.com. Interested users come and take a look! Xuexin.com usage tutorial: How to check your academic qualifications on Xuexin.com 1. Xuexin.com entrance: https://www.chsi.com.cn/ 2. Website query: Step 1: Click on the Xuexin.com address above to enter the homepage Click [Education Query]; Step 2: On the latest webpage, click [Query] as shown by the arrow in the figure below; Step 3: Then click [Login Academic Credit File] on the new page; Step 4: On the login page Enter the information and click [Login];

Three Ways to Fix Edge Your Connection Isn't Private Three Ways to Fix Edge Your Connection Isn't Private Mar 13, 2024 pm 01:30 PM

When you use the Edge browser to access web pages, have you ever encountered a prompt that your connection is not a dedicated connection, causing web browsing to fail? How is this going? Many friends don’t know how to deal with this problem. You can take a look at the following three solutions. Method 1 (simple and crude): In the edge browser, you can try to solve the problem of the website being inaccessible by entering the settings and turning off the security function, and then blocking location permissions in the website permissions. It is important to note that the effectiveness and duration of this approach may vary, and specific effects cannot be determined. After restarting your browser, you can try visiting the website to see if the issue is resolved. Method 2: Adjust the keyboard to English input

Windows cannot access the specified device, path, or file Windows cannot access the specified device, path, or file Jun 18, 2024 pm 04:49 PM

A friend's computer has such a fault. When opening "This PC" and the C drive file, it will prompt "Explorer.EXE Windows cannot access the specified device, path or file. You may not have the appropriate permissions to access the project." Including folders, files, This computer, Recycle Bin, etc., double-clicking will pop up such a window, and right-clicking to open it is normal. This is caused by a system update. If you also encounter this situation, the editor below will teach you how to solve it. 1. Open the registry editor Win+R and enter regedit, or right-click the start menu to run and enter regedit; 2. Locate the registry "Computer\HKEY_CLASSES_ROOT\PackagedCom\ClassInd"

How to connect OnePlus watch to Bluetooth headset_How to connect OnePlus watch to Bluetooth headset How to connect OnePlus watch to Bluetooth headset_How to connect OnePlus watch to Bluetooth headset Mar 23, 2024 pm 01:16 PM

1. Place the earphones in the earphone box and keep the lid open. Press and hold the button on the box to enter the pairing state of the earphones. 2. Turn on the watch music function and select Bluetooth headphones, or select Bluetooth headphones in the watch settings function. 3. Select the headset on the watch to pair successfully.

How to update MSI graphics card driver? MSI graphics card driver download and installation steps How to update MSI graphics card driver? MSI graphics card driver download and installation steps Mar 13, 2024 pm 08:49 PM

MSI graphics cards are the mainstream graphics card brand on the market. We know that graphics cards need to install drivers to achieve performance and ensure compatibility. So how to update the MSI graphics card driver to the latest version? Generally, MSI graphics card drivers can be downloaded and installed from the official website. Let’s find out more below. Graphics card driver update method: 1. First, we enter the "MSI official website". 2. After entering, click the "Search" button in the upper right corner and enter your graphics card model. 3. Then find the corresponding graphics card and click on the details page. 4. Then enter the "Technical Support" option above. 5.Finally go to “Driver & Download”

See all articles