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;
}
相关推荐
SmartRadio5 小时前
CH585M+MK8000、DW1000 (UWB)+W25Q16的低功耗室内定位设计
c语言·开发语言·uwb
cpp_25018 小时前
P2708 硬币翻转
数据结构·c++·算法·题解·洛谷
踩坑记录9 小时前
leetcode hot100 11.盛最多水的容器 medium 双指针
算法·leetcode·职场和发展
圣保罗的大教堂9 小时前
leetcode 865. 具有所有最深节点的最小子树 中等
leetcode
X在敲AI代码11 小时前
LeetCode 基础刷题D2
算法·leetcode·职场和发展
源代码•宸11 小时前
Leetcode—1929. 数组串联&&Q1. 数组串联【简单】
经验分享·后端·算法·leetcode·go
weixin_4617694011 小时前
15. 三数之和
c++·算法·leetcode·三数之和
千金裘换酒11 小时前
LeetCode 链表两数相加
算法·leetcode·链表
SmartRadio12 小时前
在CH585M代码中如何精细化配置PMU(电源管理单元)和RAM保留
linux·c语言·开发语言·人工智能·单片机·嵌入式硬件·lora
独自破碎E13 小时前
二分查找-I
leetcode