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;
}
相关推荐
abant21 小时前
leetcode 114 二叉树变链表
算法·leetcode·链表
XiYang-DING1 小时前
【LeetCode】 225.用队列实现栈
算法·leetcode·职场和发展
派大星~课堂2 小时前
【力扣-148. 排序链表】Python笔记
python·leetcode·链表
小白菜又菜2 小时前
Leetcode 657. Robot Return to Origin
python·leetcode·职场和发展
_深海凉_2 小时前
LeetCode热题100-环形链表
算法·leetcode·链表
memcpy03 小时前
LeetCode 904. 水果成篮【不定长滑窗+哈希表】1516
算法·leetcode·散列表
老四啊laosi3 小时前
[双指针] 8. 四数之和
算法·leetcode·四数之和
田梓燊3 小时前
leetcode 41
数据结构·算法·leetcode
_深海凉_3 小时前
LeetCode热题100-三数之和
算法·leetcode·职场和发展
y = xⁿ3 小时前
【LeetCode】双指针合集
算法·leetcode