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;
}
相关推荐
white-persist1 分钟前
【攻防世界】reverse | simple-check-100 详细题解 WP
c语言·开发语言·汇编·数据结构·c++·python·算法
长安er9 分钟前
LeetCode 01 背包 & 完全背包 题型总结
数据结构·算法·leetcode·动态规划·背包问题
小南家的青蛙13 分钟前
LeetCode第2658题 - 网格图中鱼的最大数目
算法·leetcode·职场和发展
☆cwlulu1 小时前
C/C++ 内存分配函数详解
c语言·c++
夏鹏今天学习了吗2 小时前
【LeetCode热题100(73/100)】买卖股票的最佳时机
算法·leetcode·职场和发展
Voyager_42 小时前
算法学习记录17——力扣“股票系列题型”
学习·算法·leetcode
XFF不秃头3 小时前
【力扣刷题笔记-在排序数组中查找元素的第一个和最后一个位置】
c++·笔记·算法·leetcode
程芯带你刷C语言简单算法题3 小时前
Day30~实现strcmp、strncmp、strchr、strpbrk
c语言·学习·算法·c
im_AMBER4 小时前
Leetcode 79 最佳观光组合
笔记·学习·算法·leetcode