79. Word Search

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

class Solution {
public:
    int m, n;
    bool exist(vector<vector<char>>& board, string word) {
        m = board.size();   if (m == 0) return false;
        n = board[0].size();    if (n == 0) return false;
        if (word == "") return true;
        for (int i = 0; i < m; i++)
            for (int j = 0; j < n; j++)
                if (helper(board, word, 0, i, j))
                    return true;
        return false;
    }
    bool helper(vector<vector<char>>& board, const string& word, int start, int i, int j) {
        if (board[i][j] != word[start]) return false;
        if (start+1 == word.length()) return true;
        
        char c = board[i][j];
        board[i][j] = 0;
        int dirs[] = { -1, 0, 1, 0, -1 };
        for (int d = 0; d < 4; d++) {
            int x = i + dirs[d];
            int y = j + dirs[d+1];
            if (x >= 0 && x < m && y >= 0 && y < n && helper(board, word, start+1, x, y))
                return true;
        }
        board[i][j] = c;
        return false;
    }
};

 

posted @ 2018-05-19 15:14  JTechRoad  阅读(100)  评论(0编辑  收藏  举报