码迷,mamicode.com
首页 > 其他好文 > 详细

79. Word Search

时间:2018-05-19 17:03:28      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:cto   oar   esc   http   color   nbsp   div   .com   tar   

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;
    }
};

 

79. Word Search

标签:cto   oar   esc   http   color   nbsp   div   .com   tar   

原文地址:https://www.cnblogs.com/JTechRoad/p/9060410.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!