LeetCode //C - 79. Word Search

Given an m x n grid of characters board and a string word , return true if word exists in the grid.

The word can 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.

Example 1:

Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
Output: true

Example 2:

Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE"
Output: true

Example 3:

Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB"
Output: false

Constraints:
  • m == board.length
  • n = board[i].length
  • 1 <= m, n <= 6
  • 1 <= word.length <= 15
  • board and word consists of only lowercase and uppercase English letters.

From: LeetCode

Link: 79. Word Search


Solution:

Ideas:

Main Idea:

The main concept here is to use Depth First Search (DFS) to explore the board. Starting from each cell, the algorithm tries to construct the word by moving either horizontally or vertically through adjacent cells. While doing so, the algorithm makes sure not to use the same cell more than once.

Details:
1. Starting Point:

  • The function exist iterates through every cell in the board. For each cell, it checks if the word can be formed starting from that cell by invoking the dfs function.

2. DFS Function (dfs):

  • The purpose of this function is to explore all possible paths from a given cell (i, j) to see if the word can be constructed.
  • It first checks if the current cell's value matches the current character of the word (word[index]). If not, it returns false.
  • If the cell's value matches the last character of the word, it means the word is found, and it returns true.
  • If the cell's value matches the current character but is not the last character of the word, it proceeds to search in all four directions: up, down, left, and right.

3. Avoiding Revisiting the Same Cell:

  • To ensure the same cell is not used more than once, the function temporarily marks the current cell as visited by setting its value to 0 (or any character that is not a valid board character). This is a kind of "backtracking".
  • After exploring all paths from the current cell, its original value is restored, which undoes the "marking".

4. Result:

  • If at any point during the search, the dfs function finds the word, it returns true to the main exist function.
  • If the word is not found starting from any cell in the board, the exist function returns false.
Code:
c 复制代码
bool dfs(char** board, int i, int j, char* word, int index, int boardSize, int boardColSize) {
    // Base case: if the current position is out of bounds or the current character does not match
    if (i < 0 || i >= boardSize || j < 0 || j >= boardColSize || board[i][j] != word[index]) {
        return false;
    }

    // If we've reached the end of the word, then we've found a match
    if (index == strlen(word) - 1) {
        return true;
    }

    char tmp = board[i][j];
    board[i][j] = 0;  // Mark the cell as visited

    // Recursively search for the next character in all four directions (up, down, left, right)
    bool found = dfs(board, i + 1, j, word, index + 1, boardSize, boardColSize)
              || dfs(board, i - 1, j, word, index + 1, boardSize, boardColSize)
              || dfs(board, i, j + 1, word, index + 1, boardSize, boardColSize)
              || dfs(board, i, j - 1, word, index + 1, boardSize, boardColSize);

    board[i][j] = tmp;  // Restore the cell value after the DFS

    return found;
}

bool exist(char** board, int boardSize, int* boardColSize, char* word) {
    for (int i = 0; i < boardSize; i++) {
        for (int j = 0; j < boardColSize[0]; j++) {
            // Start the DFS search from each cell in the board
            if (dfs(board, i, j, word, 0, boardSize, boardColSize[0])) {
                return true;
            }
        }
    }
    return false;
}
相关推荐
子豪-中国机器人1 分钟前
C++ 信息学奥赛总复习题
java·jvm·算法
学习噢学个屁27 分钟前
基于STM32物联网智能鱼缸智能家居系统
c语言·stm32·单片机·嵌入式硬件·物联网·智能家居
全干engineer1 小时前
web3-基于贝尔曼福特算法(Bellman-Ford )与 SMT 的 Web3 DeFi 套利策略研究
算法·金融·web3·去中心化·区块链·智能合约
Splendid2 小时前
Geneformer:基于Transformer的基因表达预测深度学习模型
javascript·算法
愿所愿皆可成2 小时前
机器学习之聚类Kmeans算法
算法·机器学习·kmeans·聚类
幻奏岚音2 小时前
统计学(第8版)——假设检验学习笔记(考试用)
笔记·学习·算法
hie988942 小时前
基于matlab策略迭代和值迭代法的动态规划
算法·动态规划
Coovally AI模型快速验证2 小时前
SFTrack:面向警务无人机的自适应多目标跟踪算法——突破小尺度高速运动目标的追踪瓶颈
人工智能·神经网络·算法·yolo·计算机视觉·目标跟踪·无人机
Brduino脑机接口技术答疑2 小时前
脑机新手指南(七):OpenBCI_GUI:从环境搭建到数据可视化(上)
人工智能·算法·脑机接口·新手入门
真的很上进3 小时前
2025最全TS手写题之partial/Omit/Pick/Exclude/Readonly/Required
java·前端·vue.js·python·算法·react·html5