C/C++教程

leetcode算法题--Word Search

本文主要是介绍leetcode算法题--Word Search,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

原题链接:https://leetcode.com/problems/word-search/

class Solution {
public:
    int n, m;
    vector<vector<char>> board;
    vector<vector<int>> visited;
    string word;
    bool exist(vector<vector<char>>& _board, string _word) {
        board = _board;
        word = _word;
        m = board.size(), n = board[0].size();
        visited = vector<vector<int>> (m, vector<int>(n, 0));
        for (int i = 0; i < m; i ++ ) {
            for (int j = 0; j < n; j ++ ) {
                if (board[i][j] == word[0]) {
                    if (dfs(1, i, j)) {
                        return true;
                    }
                }   
            }
        }
        return false;
    }
    
    bool dfs(int index, int r, int c) {
        if (index == word.size()) return true;
        visited[r][c] = 1;
        int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
        
        for (int i = 0; i < 4; i ++ ) {
            if (r + dx[i] >= 0 && r + dx[i] < m && c + dy[i] >= 0 && c + dy[i] < n && visited[r + dx[i]][c + dy[i]] != 1 && board[r + dx[i]][c + dy[i]] == word[index]) {
                if (dfs(index+1, r + dx[i], c + dy[i])) {
                    return true;
                }
            }
        }
        visited[r][c] = 0;
        return false;
    }
};
这篇关于leetcode算法题--Word Search的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!