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

79. Word Search

时间:2018-09-22 22:24:31      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:tor   成功   let   sam   dex   str   重复   匹配   遍历   

Given a 2D board and a word, find if the word exists in the grid.

The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.

Example:

board =
[
  [‘A‘,‘B‘,‘C‘,‘E‘],
  [‘S‘,‘F‘,‘C‘,‘S‘],
  [‘A‘,‘D‘,‘E‘,‘E‘]
]

Given word = "ABCCED", return true.
Given word = "SEE", return true.
Given word = "ABCB", return false.
class Solution {
    public:
        //遍历回溯,采取一个特殊处理:如果匹配到相同字符,则将该字符先置为‘0‘,回溯时恢复原字符,以免重复使用
    bool exist(vector<vector<char>>& board, string word) {
        if(board.size()==0){
                return false;
        }
        for(int i=0; i<board.size(); ++i){
            for(int j=0; j<board[0].size(); ++j){
                if(dfs(board, i, j, word, 0))
                    return true;
            }
        }
        return false;
    }
    bool dfs(vector<vector<char> >& board, int i, int j, string word, int index){
        if(index>=word.size())         //搜索完成条件
            return true;
        if(i<0||i>=board.size()||j<0||j>=board[0].size())    //搜索结束(不成功)条件
            return false;
        if(board[i][j]!=word[index]){   //当前不匹配
            return false;
        }
        char temp = board[i][j];         //当前匹配,并从邻域搜索是否匹配
        board[i][j]=0;
        bool res = dfs(board, i+1, j, word, index+1)||dfs(board, i, j+1, word, index+1)||dfs(board, i-1, j, word, index+1)||dfs(board, i, j-1, word, index+1);
        board[i][j]=temp;
        return res;
    }
};

 

79. Word Search

标签:tor   成功   let   sam   dex   str   重复   匹配   遍历   

原文地址:https://www.cnblogs.com/duan-decode/p/9691419.html

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