单词搜索II

给定一个 m x n 二维字符网格 board 和一个单词(字符串)列表 words,找出所有同时在二维网格和字典中出现的单词。

单词必须按照字母顺序,通过 相邻的单元格 内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母在一个单词中不允许被重复使用。

在这里插入图片描述

输入:board = [[“o”,“a”,“a”,“n”],[“e”,“t”,“a”,“e”],[“i”,“h”,“k”,“r”],[“i”,“f”,“l”,“v”]], words = [“oath”,“pea”,“eat”,“rain”]
输出:[“eat”,“oath”]

思路:DFS

对words数组的每一个元素在board中进行DFS回溯搜索即可。
超时

class Solution {
public:
    int dx[4] = {-1, 1, 0, 0};
    int dy[4] = {0, 0, -1, 1};
    bool dfs(vector<vector<char>>& board, string s, int i, int j, int idx)
    {
        if (idx == s.size()) return true;
        int m = board.size(), n = board[0].size();
        for (int k = 0; k < 4; ++k) {
            int x = i + dx[k];
            int y = j + dy[k];
            if (x >= 0 && x < m && y >= 0 && y < n && board[x][y] == s[idx]) {
                board[x][y] = '0';
                if (dfs(board, s, x, y, idx + 1)) {
                    board[x][y] = s[idx];
                    return true;
                }
                board[x][y] = s[idx];
            }
        }
        return false;
    }
    vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
        vector<string> ret;
        int m = board.size(), n = board[0].size();
        for (string s : words) {
            bool find = false;
            for (int i = 0; i < m && !find; ++i) {
                for (int j = 0; j < n && !find; ++j) {
                    if (board[i][j] == s[0]) {
                        board[i][j] = '0';
                        if (dfs(board, s, i, j, 1)) {
                            find = true;
                            ret.emplace_back(s);
                        }
                        board[i][j] = s[0];
                    }
                }
            }
        }
        return ret;
    }
};

思路二:Trie树 + DFS

struct TrieNode {
  vector<TrieNode*> children;
  string* word;
  TrieNode() : word(nullptr), children(26) {};
  ~TrieNode() {
    for (const auto& child : children)
      delete child;
  }
};

class Solution {
public:
  vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {

    const int m = board.size(), n = board[0].size();

    TrieNode root;
    for (auto& word : words) {
      TrieNode* p = &root;
      for (const auto& c : word) {
        if (!p->children[c - 97])
          p->children[c - 97] = new TrieNode();
        p = p->children[c - 97];
      }
      p->word = &word;
    }

    vector<string> ans;
    function<void(int, int, int, TrieNode*)> walk = [&](int x, int y, int d, TrieNode* p) {
      if (x < 0 || y < 0 || x == n || y == m || !board[y][x])
        return;

      const char c = board[y][x];
      p = p->children[c - 97];
      if (!p) return;
      
      if (p->word) {
        ans.emplace_back(*p->word);
        p->word = nullptr;
      }

      board[y][x] = 0;

      walk(x - 1, y, d + 1, p);
      walk(x + 1, y, d + 1, p);
      walk(x, y - 1, d + 1, p);
      walk(x, y + 1, d + 1, p);

      board[y][x] = c;
    };

    for (int y = 0; y < m; ++y)
      for (int x = 0; x < n; ++x)
        walk(x, y, 0, &root);

    return ans;
  }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,编写单词搜索软件可以分为以下几个步骤: 1. 读取文本文件中的单词和字符矩阵 可以使用C标准库中的文件读取函数,如fopen、fread等函数读取文件内容,将单词和字符矩阵分别存储到数组中。 2. 实现单词搜索功能 可以采用暴力搜索的方式,遍历矩阵中的每个字符,以该字符为起点,依次向其上、下、左、右、左上、左下、右上和右下八个方向搜索,直到找到单词或者搜索到矩阵的边界。 3. 输出搜索结果 将搜索得到的单词输出到文件或者控制台上。 下面是一个简单的示例代码,用于实现单词搜索功能: ```c #include <stdio.h> #include <string.h> #define MAX_WORD_LEN 20 #define MAX_ROWS 10 #define MAX_COLS 10 char words[100][MAX_WORD_LEN + 1]; char matrix[MAX_ROWS][MAX_COLS]; void search_word(int r, int c, int row, int col, int len, char *word) { if (len == strlen(word)) { printf("Found word: %s\n", word); return; } if (r < 0 || r >= row || c < 0 || c >= col) return; if (matrix[r][c] != word[len]) return; char temp = matrix[r][c]; matrix[r][c] = ' '; search_word(r - 1, c, row, col, len + 1, word); search_word(r + 1, c, row, col, len + 1, word); search_word(r, c - 1, row, col, len + 1, word); search_word(r, c + 1, row, col, len + 1, word); search_word(r - 1, c - 1, row, col, len + 1, word); search_word(r - 1, c + 1, row, col, len + 1, word); search_word(r + 1, c - 1, row, col, len + 1, word); search_word(r + 1, c + 1, row, col, len + 1, word); matrix[r][c] = temp; } int main() { int n, row, col; printf("Enter the number of words: "); scanf("%d", &n); printf("Enter the words:\n"); for (int i = 0; i < n; i++) scanf("%s", words[i]); printf("Enter the number of rows: "); scanf("%d", &row); printf("Enter the number of cols: "); scanf("%d", &col); printf("Enter the matrix:\n"); for (int i = 0; i < row; i++) scanf("%s", matrix[i]); for (int i = 0; i < n; i++) { for (int j = 0; j < row; j++) { for (int k = 0; k < col; k++) { if (matrix[j][k] == words[i][0]) search_word(j, k, row, col, 0, words[i]); } } } return 0; } ``` 注意:以上仅为示例代码,还有很多可以优化的地方,比如可以使用Trie树来存储单词,使用更高效的搜索算法等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值