Word Search II

Given an m x n board of characters and a list of strings words, return all words on the board.

Each word must be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.

Example:

Input: board = [["o","a","a","n"],["e","t","a","e"],["i","h","k","r"],["i","f","l","v"]], words = ["oath","pea","eat","rain"]
Output: ["eat","oath"]

Approach:

C++

#include <bits/stdc++.h>
using namespace std;

vector<stringres;
struct TrieNode
{
    struct TrieNode *child[26];
    bool isword;
    int id;
    TrieNode()
    {
        isword = false;
        id = -1;
        for (int i = 0i < 26i++)
            child[i] = NULL;
    }
};
TrieNode *root;
void insert(string wordint x)
{
    struct TrieNode *temp = root;
    for (int i = 0i < word.size(); i++)
    {
        int j = word[i] - 'a';
        if (temp->child[j] == NULL)
            temp->child[j] = new TrieNode();
        temp = temp->child[j];
    }
    temp->isword = true;
    temp->id = x;
}
void dfs(TrieNode *pvector<vector<char>> &board,
         int iint jvector<string&words)
{
    if (i < 0 || i >= board.size() || j < 0 || j >= board[0].size())
    {
        if (p->isword && p->id != -1)
        {
            res.push_back(words[p->id]);
            p->id = -1;
        }
        return;
    }
    if (p->isword && p->id != -1)
    {
        res.push_back(words[p->id]);
        p->id = -1;
    }
    for (int k = 0k < 26k++)
    {
        if (p->child[k] != NULL && (k == (int)(board[i][j] - 'a')))
        {
            board[i][j] = '#';
            dfs(p->child[k], boardi + 1jwords);
            dfs(p->child[k], boardij + 1words);
            dfs(p->child[k], boardi - 1jwords);
            dfs(p->child[k], boardij - 1words);
            board[i][j] = (char)(k + 'a');
        }
    }
    return;
}
vector<stringfindWords(vector<vector<char>> &board,
                         vector<string&words)
{
    root = new TrieNode();
    for (int i = 0i < words.size(); i++)
        insert(words[i]i);
    for (int i = 0i < board.size(); i++)
    {
        for (int j = 0j < board[0].size(); j++)
        {
            dfs(rootboardijwords);
        }
    }
    reverse(res.begin(), res.end());
    return res;
}

int main()
{
    vector<vector<char>> board = {{'o''a''a''n'},
                                  {'e''t''a''e'},
                                  {'i''h''k''r'},
                                  {'i''f''l''v'}};
    vector<stringwords = {"oath""pea""eat""rain"};

    vector<stringres = findWords(boardwords);

    cout << "[";
    for (int i = 0i < res.size() - 1i++)
    {
        cout << res[i] << ",";
    }
    cout << res[res.size() - 1] << "]";

    return 0;
}


No comments:

Post a Comment