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

79. Word Search

时间:2018-12-03 15:32:43      阅读:88      评论:0      收藏:0      [点我收藏+]

标签:lse   vector   boa   for   color   public   sea   return   exist   

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;
        for (int i = 0; i < m; i++)
            for (int j = 0; j < n; j++)
                if (dfs(board, word, 0, i, j))
                    return true;
        return false;
    }
    bool dfs(vector<vector<char>>& board, string& word, int begin, int i, int j) {
        static int dirs[] = { -1, 0, 1, 0, -1};
        if (begin == word.length()) return true;
        if (i < 0 || i >= m || j < 0 || j >= n || board[i][j] != word[begin])
            return false;
        char saved = board[i][j];
        board[i][j] =  ;
        for (int k = 0; k < 4; k++) {
            if (dfs(board, word, begin+1, i+dirs[k], j+dirs[k+1]))
                return true;
        }
        board[i][j] = saved;
        return false;
    }
};

 

79. Word Search

标签:lse   vector   boa   for   color   public   sea   return   exist   

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

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