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;
}
相关推荐
阿捏利1 小时前
C Primer Plus 第6版 编程练习——第7章(上)
c语言·编程题·c primer plus
是白可可呀1 小时前
LeetCode 169. 多数元素
leetcode
jz_ddk1 小时前
[实战]调频(FM)和调幅(AM)信号生成(完整C语言实现)
c语言·算法·信号处理
码农Cloudy.2 小时前
C语言<数据结构-链表>
c语言·数据结构·链表
YuTaoShao3 小时前
【LeetCode 热题 100】148. 排序链表——(解法二)分治
java·算法·leetcode·链表
星竹晨L3 小时前
C语言——预处理详解
c语言·开发语言
lightqjx3 小时前
【数据结构】顺序表(sequential list)
c语言·开发语言·数据结构·算法
小立爱学习4 小时前
Linux 内存管理之address_space
linux·c语言
蒟蒻小袁4 小时前
力扣面试150题--全排列
算法·leetcode·面试
緈福的街口5 小时前
【leetcode】2236. 判断根节点是否等于子节点之和
算法·leetcode·职场和发展