Finding words in a matrix in JavaScript

JavascriptWeb DevelopmentFront End Technology

We are required to write a JavaScript function that takes in an array of arrays of characters as the first argument and a string as the second argument.

The function should find out whether there exist characters in the matrix, non-repeating combination of which yields the string provided to the function as the second argument.

If there exists such a combination, our function should return true, false otherwise.

For example −

If the input array and the string are −

const arr = [
   ['s', 'd', 'k', 'e'],
   ['j', 'm', 'o', 'w'],
   ['y', 'n', 'l']
];
const str = 'don';

Then the output should be −

const output = false;

Example

Following is the code −

const arr = [
   ['s', 'd', 'k', 'e'],
   ['j', 'm', 'o', 'width'],
   ['y', 'n', 'l']
];
const str = 'don';
const containsWord = (arr = [], str = '') => {
   if (arr.length === 0){
      return false;
   };
   const height = arr.length;
   const width = arr[0].length;
   const dirs = [[-1, 0], [0, 1], [1, 0], [0, -1]];
   const tryWord = (x, y, k) => {
      if (arr[x][y] !== str[k]) return false;
      if (k === str.length - 1) return true;
      arr[x][y] = '*';
      for (const [dx, dy] of dirs) {
         const i = x + dx;
         const j = y + dy;
         if (i >= 0 && i < height && j >= 0 && j < width) {
            if (tryWord(i, j, k + 1)) return true;
         }
      }
      arr[x][y] = str[k]; // reset
      return false;
   };
   for (let i = 0; i < height; i++) {
      for (let j = 0; j < width; j++) {
         if (tryWord(i, j, 0)) return true;
      }
   }
   return false;
};
console.log(containsWord(arr, str));

Output

Following is the console output −

false
raja
Published on 19-Jan-2021 06:23:06
Advertisements