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

Word Search

时间:2016-04-13 23:49:47      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:

iven 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.

For example,
Given board =

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

word = "ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false.

回溯法:

class Solution {
public:
    bool search(vector<vector<char> > &board,const string word,int i,int j,int pos){
        if(pos==word.size())return true;
        if(i<0||i>=board.size()||j<0||j>=board[i].size())return false;
        char ch=board[i][j];
        if(ch==word[pos]){
            board[i][j]=#;//标记为已访问过的点
            if(search(board,word,i-1,j,pos+1)||search(board,word,i+1,j,pos+1)
                ||search(board,word,i,j-1,pos+1)||search(board,word,i,j+1,pos+1)) return true;
            board[i][j]=ch;//回溯失败则变成上一个状态
        }
        return false;
    }
    bool exist(vector<vector<char> >& board, string word) {
        for(int i=0;i<board.size();i++){
            for(int j=0;j<board[i].size();j++){
                if(search(board,word,i,j,0)) return true;//寻找第一个匹配的位置,然后通过回溯求解
            }
        }
        return false;
    }
};

 

Word Search

标签:

原文地址:http://www.cnblogs.com/wqkant/p/5389050.html

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