[LeetCode] Word Search

★ 题目

https://leetcode.com/problems/word-search/

Given a 2D board and a word, find if the word exists in the grid.

The word can be constructed from letters of sequentially adjacent cell, where “adjacent” cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.

For example,
Given board =

[
  ['A','B','C','E'],
  ['S','F','C','S'],
  ['A','D','E','E']
]

word = "ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false.

★ 代码

87 / 87 test cases passed.
Runtime: 10 ms
int dir[4][2] = {
    {0, -1}, // up
    {0, 1}, //down
    {-1, 0}, //left
    {1, 0} // right        
};

#define rint register int
int maxRow = 0;
int maxCol = 0;

bool findChar(char** board, bool** visited, int row, int col, char* word, int offset, int len) {
    if (offset + 1 == len) return true;
    visited[row][col] = true;
    char c = word[offset+1];
    for (rint i = 0; i < 4; i++) {
        int row2 = row + dir[i][1];
        int col2 = col + dir[i][0];
        if (row2 < 0 || row2 >= maxRow || col2 < 0 || col2 >= maxCol) continue;
        if (visited[row2][col2]) continue;
        if (c == board[row2][col2] && findChar(board, visited, row2, col2, word, offset+1, len)) {
            return true;
        }
    }
    visited[row][col] = false;
    return false;
}
bool exist(char** board, int boardRowSize, int boardColSize, char* word) {
    int len = strlen(word);
    if (len == 0) return false;

    maxRow = boardRowSize;
    maxCol = boardColSize;

    bool** visited = (bool**)malloc(boardRowSize*sizeof(bool*));
    for (rint i = 0; i < boardRowSize; i++) {
        visited[i] = (bool*)malloc(boardColSize*sizeof(bool));
        memset(visited[i], 0, boardColSize*sizeof(bool));
    }

    int ret = false;
    for (rint i = 0; i < boardRowSize; i++) {
        for (rint j = 0; j < boardColSize; j++) {
            if (board[i][j] == word[0]) {
                if (findChar(board, visited, i, j, word, 0, len)) {
                    ret = true;
                    break;
                }
            }
        }
        if (ret) break;
    }
    for (rint i = 0; i < boardRowSize; i++) {
        free(visited[i]);
    }
    free(visited);
    return ret;
}

猜你喜欢

转载自blog.csdn.net/u013553529/article/details/79029435