C语言 | Leetcode C语言题解之第79题单词搜索

题目:

题解:

cpp 复制代码
int directions[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};

bool check(char** board, int boardSize, int boardColSize, int** visited, int i, int j, char* s, int sSize, int k) {
    if (board[i][j] != s[k]) {
        return false;
    } else if (k == sSize - 1) {
        return true;
    }
    visited[i][j] = true;
    bool result = false;
    for (int sel = 0; sel < 4; sel++) {
        int newi = i + directions[sel][0], newj = j + directions[sel][1];
        if (newi >= 0 && newi < boardSize && newj >= 0 && newj < boardColSize) {
            if (!visited[newi][newj]) {
                bool flag = check(board, boardSize, boardColSize, visited, newi, newj, s, sSize, k + 1);
                if (flag) {
                    result = true;
                    break;
                }
            }
        }
    }
    visited[i][j] = false;
    return result;
}

bool exist(char** board, int boardSize, int* boardColSize, char* word) {
    int** visited = malloc(sizeof(int*) * boardSize);
    for (int i = 0; i < boardSize; i++) {
        visited[i] = malloc(sizeof(int) * boardColSize[0]);
        memset(visited[i], 0, sizeof(int) * boardColSize[0]);
    }
    int wordSize = strlen(word);
    for (int i = 0; i < boardSize; i++) {
        for (int j = 0; j < boardColSize[0]; j++) {
            bool flag = check(board, boardSize, boardColSize[0], visited, i, j, word, wordSize, 0);
            if (flag) {
                return true;
            }
        }
    }
    return false;
}
相关推荐
枫景Maple4 小时前
LeetCode 2297. 跳跃游戏 VIII(中等)
算法·leetcode
hjyowl5 小时前
题解:AT_abc407_c [ABC407C] Security 2
c语言·开发语言·算法
old_power7 小时前
UCRT 和 MSVC 的区别(Windows 平台上 C/C++ 开发相关)
c语言·c++·windows
緈福的街口7 小时前
【leetcode】3. 无重复字符的最长子串
算法·leetcode·职场和发展
@老蝴8 小时前
C语言 — 编译和链接
c语言·开发语言
LunaGeeking9 小时前
三分算法与DeepSeek辅助证明是单峰函数
c语言·c++·算法·编程·信奥赛·ai辅助学习·三分
小刘不想改BUG11 小时前
LeetCode 70 爬楼梯(Java)
java·算法·leetcode
whoarethenext11 小时前
使用 C/C++ 和 OpenCV 实现滑动条控制图像旋转
c语言·c++·opencv
sz66cm13 小时前
LeetCode刷题 -- 542. 01矩阵 基于 DFS 更新优化的多源最短路径实现
leetcode·矩阵·深度优先