4ms solution with optimize comment


  • 0
    J
    bool canForward(char** board, int boardRowSize, int boardColSize, char* word, int i, int j, int step) {
        if (board[i][j] == word[step]) {
            char c = board[i][j];
            board[i][j] = '#';
            if (step == strlen(word) - 1) {
                return true;
            }
            // judge condition before method call
            if ( (i-1) >= 0 && canForward(board, boardRowSize, boardColSize, word, i-1, j, step+1) ||
                (i+1) < boardRowSize && canForward(board, boardRowSize, boardColSize, word, i+1, j, step+1) ||
                (j-1) >= 0 && canForward(board, boardRowSize, boardColSize, word, i, j-1, step+1) ||
                (j+1) < boardColSize && canForward(board, boardRowSize, boardColSize, word, i, j+1, step+1)) {
                board[i][j] = c;
                return true;
            }
            board[i][j] = c;
        }
        return false;
    }
    bool exist(char** board, int boardRowSize, int boardColSize, char* word) {
        int len = strlen(word);
        if ( len == 0) {
            return true;
        }
        if (boardRowSize * boardColSize < len) { // exit early.
            return false;
        }
        int step = 0;
        for (int i = 0; i < boardRowSize; i++) {
            for (int j = 0; j < boardColSize; j++) {
                if (board[i][j] == word[step]) { // judge before call canForward recursively 
                    if (canForward(board, boardRowSize, boardColSize, word, i, j, step)) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.