Check if a given string can be formed using characters of adjacent cells of a matrix


Let's first understand the meaning of neighbour cells in matrices. To determine how each component fits into your two-dimensional matrix structure visualize each enclosed unit as being encompassed by almost eight adjacent elements positioned across/from them both diagonal directions in addition to vertical/horizontal ones. An example observation can be made about lattice size - the smallest circular enclosure in this design has nine components.(from left-to-right & up-to-down)Cell [row=9,col=8] -- within reach from [row=8,col=7],...[row=10,col=8], and so forth. This intricate connection network links these adjacent components where they share edges or corners; creating a well-defined matrix structure stepping up its capacity for the execution of diverse operations and computations.

Method

  • Iterative Method

  • Iterative Method II

Iterative Method

The iterative method is a strategy for addressing problems that involves performing loops or iterations. This technique can be used, for example, to determine whether a particular string can be created from the characters in nearby matrix cells.

Usually, the problem statement includes a target string and a character matrix. The goal is to identify whether the target string can be generated by moving up, down, left, or right across adjacent matrix cells.

Syntax

The syntax for determining whether string can be created using characters from adjacent matrix cells, assuming the matrix is represented as a 2D array, and the given string is saved in a variable called input String.

  • Set Boolean function string Found to false.

  • Use two nested loops to loop through all cell in matrix.

  • For each cell, check whether the current character in input string matches the current cell of the matrix.

  • If match is found, recursively check whether remaining characters in input string can be produced using adjacent cells of the current cell in matrix.

  • If complete input string can be produced using nearby matrix cells, change string Found variable to true and exit the loop.

  • When this loop is completed, string Found returns true if input string can be produced using neighbouring cells of matrix, and false otherwise.

Algorithm

  • Step 1 − Change the value of the Boolean variable "found" to false.

  • Step 2 − Review each matrix cell individually.

  • Step 3 − If the first character of the required string matches the current cell, we use the points of the current cell and the index of the following character in the string to perform the recursive function "search."

  • Step 4 − Before going back to, the "found" variable must be set to true if the index of the "search" function is the equal to the length of the required string.

  • Step 5 − We Check the characters in the neighboring cells by looping over them. If any of them match the string's next character, perform the "search" method again with a higher index and the new coordinates.

  • Step 6 − If none of the neighboring cells match the next character in the string, exit the function.

Example 1

The can_form_string method iteratively determines whether the provided string can be produced using neighbouring matrix cells starting from the specified cell (i,j). It returns true if adjacent cells can be utilised to create the entire string; otherwise, it returns false.

The string to be tested is hard-coded as "abcfi" and the can_form_string function is invoked for each cell in the matrix in the main function. If a match is found, the application generates a message indicating that the string can be constructed using neighbouring matrix cells. A message to that effect is produced if the string cannot be created using neighbouring matrix cells.

#include <iostream>
#include <cstring>
using namespace std;

const int N = 3; 
char matrix[N][N] = {
   {'a', 'b', 'c'},
   {'d', 'e', 'f'},
   {'g', 'h', 'i'}
}; 

bool can_form_string(int i, int j, const char* str) {
   if (*str == '\0') {
      return true; 
   }
   if (i < 0 || i >= N || j < 0 || j >= N) {
      return false; 
   }
   if (matrix[i][j] != *str) {
      return false; 
   }
   const char* rest_of_str = str + 1; 
   return (
      can_form_string(i-1, j, rest_of_str) || 
      can_form_string(i+1, j, rest_of_str) || 
      can_form_string(i, j-1, rest_of_str) || 
      can_form_string(i, j+1, rest_of_str)    
   );
}
int main() {
   const char* str_to_check = "abcfi";
   bool result = false;
   for (int i = 0; i < N; i++) {
      for (int j = 0; j < N; j++) {
         result = can_form_string(i, j, str_to_check);
         if (result) {
            break; 
         }
      }
      if (result) {
         break; 
      }
   }
if (result) {
   cout << "The string "" << str_to_check << "" can be formed using adjacent cells of the matrix." << endl;
   } else {
      cout << "The string "" << str_to_check << "" cannot be formed using adjacent cells of the matrix." << endl;
   }
   return 0;
}

Output

The string  << str_to_check <<  can be formed using adjacent cells of the matrix.

Algorithm

The following are the stages to putting this strategy into action −

  • Step 1 − Start navigating the matrix from the top-left corner, seeking for the string's initial character that corresponds to the current cell.

  • Step 2 − If it matches, mark the current cell as visited and go to the next character of the string.

  • Step 3 − If it does not match, we go on to the next cell and repeat step 2 again.

  • Step 4 − If we are unable to locate match for next character in string at any point, return to last location and try another adjacent cell.

  • Step 5 − Return true if we can match all characters in string and get to end of it. Return false otherwise.

Example 2

The canFormString() function in this application iteratively determines whether a supplied string can be made out of the characters in adjacent matrix cells.

The procedure receives a string, a matrix, the current character's index in the string, the current row and column indices, a monitoring matrix for visited cells, and a matrix of visited cell indices. True is returned if the function created the string successfully; on the off chance that it is ineffective, it gets back misleading.

#include <iostream>
#include <vector>
#include <cstring>
using namespace std;

bool canFormString(vector<vector<char>>& matrix, string s, int i, int j, int k,
vector<vector<bool>>& visited) {

   if (k == s.length())
   return true;

   if (i < 0 || j < 0 || i >= matrix.size() || j >= matrix[0].size() ||
   visited[i][j] || matrix[i][j] != s[k])
   return false;
   visited[i][j] = true;


   bool canForm = canFormString(matrix, s, i - 1, j - 1, k + 1, visited) ||
   canFormString(matrix, s, i - 1, j, k + 1, visited) ||
   canFormString(matrix, s, i - 1, j + 1, k + 1, visited) ||
   canFormString(matrix, s, i, j - 1, k + 1, visited) ||
   canFormString(matrix, s, i, j + 1, k + 1, visited) ||
   canFormString(matrix, s, i + 1, j - 1, k + 1, visited) ||
   canFormString(matrix, s, i + 1, j, k + 1, visited) ||
   canFormString(matrix, s, i + 1, j + 1, k + 1, visited);

   visited[i][j] = false;

   return canForm;
}

int main() {
   vector<vector<char>> matrix{{'A', 'C', 'P'},
   {'A', 'O', 'E'},
   {'G', 'B', 'L'}};


   string s1 = "APPLE";
   string s2 = "BALL";
   string s3 = "GOOGLE";


   vector<vector<bool>> visited(matrix.size(), vector<bool>(matrix[0].size(), false));

   cout << s1 << " can " << (canFormString(matrix, s1, 0, 0, 0, visited) ? "" : "not ") << "be formed\n";
   cout << s2 << " can " << (canFormString(matrix, s2, 0, 0, 0, visited) ? "" : "not ") << "be formed\n";
   cout << s3 << " can " << (canFormString(matrix, s3, 0, 0, 0, visited) ? "" : "not ") << "be formed\n";

   return 0;
}

Output

APPLE can not be formed
BALL can not be formed
GOOGLE can not be formed

Conclusion

To see if given string can be created using characters from neighbouring cells of a matrix, we must first locate each element's adjacent cells. We may check if the characters in the string match characters in the adjacent cells of each element in the matrix once we've found the adjacent cells.

This method is widely used in applications such as word search puzzles or natural language processing tasks in which we need to determine whether given word can be constructed using neighbouring letters in a matrix or grid. We can efficiently tackle these types of problems and jobs if we comprehend concept of nearby cells in a matrix.

Updated on: 31-Jul-2023

81 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements