. Day 6 - Challenge 2 - Search a word in 2D grid of letters Skip to main content

Day 6 - Challenge 2 - Search a word in 2D grid of letters

Solving the Word Search Problem using JavaScript

Introduction: 

The Word Search problem is a classic puzzle where you're given a grid of letters and a target word, and you need to determine whether the word can be formed by tracing adjacent cells in the grid. In this blog post, we'll explore how to solve the Word Search problem using JavaScript. We'll cover the algorithmic approach, provide a step-by-step guide to implementation, and discuss some optimizations to make our solution more efficient.

Algorithmic Approach: 

To solve the Word Search problem, we can employ a Depth-First Search (DFS) approach. We'll traverse the grid and recursively check adjacent cells to see if the current cell matches the next letter of the target word. If it does, we continue the search from that cell. We need to keep track of the cells we've already visited to avoid revisiting them and getting stuck in an infinite loop.

Implementation Steps: 

Let's break down the implementation into steps:

  1. Define a function called exist that takes the grid, target word, and grid dimensions as parameters.
  2. Create a nested loop to iterate through each cell in the grid.
  3. For each cell, call a helper function (e.g., search) that performs the DFS search for the target word.
  4. Inside the search function, check if the current cell matches the first letter of the target word.
  5. If the letter matches, mark the cell as visited and recursively search its adjacent cells for the next letter.
  6. If the target word is found, return true. Otherwise, backtrack by marking the cell as unvisited and returning false.
  7. Repeat steps 3-6 for each adjacent cell (up, down, left, and right).
  8. If no solution is found, return false from the exist function.

Code Implementation: 

Here's a skeleton implementation of the Word Search problem in JavaScript:


function exist(board, word) {
    const rows = board.length;
    const cols = board[0].length;

    function search(row, col, index) {
        if (index === word.length) {
            return true; // Word found
        }

        if (
            row < 0 || row >= rows ||
            col < 0 || col >= cols ||
            board[row][col] !== word[index]
        ) {
            return false; // Out of bounds or mismatch
        }

        const originalChar = board[row][col];
        board[row][col] = '#'; // Mark cell as visited

        // Search in all four directions
        const found =
            search(row + 1, col, index + 1) ||
            search(row - 1, col, index + 1) ||
            search(row, col + 1, index + 1) ||
            search(row, col - 1, index + 1);

        board[row][col] = originalChar; // Revert cell to original

        return found;
    }

    for (let i = 0; i < rows; i++) {
        for (let j = 0; j < cols; j++) {
            if (search(i, j, 0)) {
                return true;
            }
        }
    }

    return false; // Word not found
}

// Example usage
const board = [
    ['A','B','C','E'],
    ['S','F','C','S'],
    ['A','D','E','E']
];
const word = "ABCCED";
console.log(exist(board, word)); // Output: true

Conclusion: 

In this blog post, we've explored the Word Search problem and implemented a solution using JavaScript. We've seen how the Depth-First Search approach can be used to navigate through the grid and find the target word. By understanding the algorithmic approach and following the step-by-step implementation guide, you can solve the Word Search problem and enhance your problem-solving skills in JavaScript.

 

Now write the same program in your favorite language in comment section. 

Other Challenges:

  1. Day 3 Challenges
  2. Day 4 Challenges
  3. Day 5 Challenges

 

Comments

Popular posts from this blog

Create app in phonegap in windows

Phonegap (Cordova) is a tool that allows creating native mobile app using HTML, CSS and Javascript. This article shows you, how to create application and deploy them to various native mobile platforms using the cordova command-line interface (CLI). Install Cordova using CLI Follow these steps to install: Download and install Node.js . Following installation, you should be able to invoke node and npm on your command line. Install the cordova module using npm utility of Node.js. The cordova module will automatically be downloaded by the npm utility.   $ npm install -g cordova Create APP: Go to the directory where you maintain your source code, and run a command such as the following: using command. Create hello app: $ cordova create hello com.example.hello HelloWorld This command will create a folder ‘HelloWorld’. All subsequent commands need to be run within the project's directory, or any subdirectories. So go to in this folder ‘cd HelloWorld’. Add the pl...

Connecting to Socket in React Native app

Connecting to a socket in a React Native app requires the use of a socket library that supports React Native. One popular library is socket.io-client . Here are the steps to connect to a socket using socket.io-client in a React Native app: Install socket.io-client by running the following command in your project directory: npm install socket.io-client 2. Import the library in your code: import io from 'socket.io-client'; 3. Create a socket instance by calling the io function and passing in the URL of the socket server: const socket = io('http://example.com'); Replace http://example.com with the URL of your socket server. 4. Add event listeners to the socket instance to handle incoming events: socket.on('connect', () => { console.log('Connected to socket server'); }); socket.on('event', (data) => { console.log('Received data:', data); }); Replace event with the name ...

Know about the Web Socket and setup WebSocket in Javascript HTML page

  WebSockets is a protocol for providing full-duplex communication channels over a single TCP connection. It allows for real-time, two-way communication between a client and a server, which makes it ideal for web applications that require continuous updates from the server or that need to send frequent updates to the server. Here are some basic information about WebSockets: WebSockets are designed to work over a single TCP connection, which means that they are more efficient than other protocols like HTTP that require multiple connections for each request/response cycle. WebSockets use a persistent connection between the client and server, which allows for real-time communication without the need for frequent polling or long-polling requests. The WebSocket protocol uses a message-based model for sending and receiving data, which means that data is transmitted as a stream of messages rather than a series of HTTP requests and responses. WebSockets support binary data transmission, wh...