leetCode刷题归纳-backtracking(79. Word Search)

来源:互联网 发布:深入浅出mysql 百度云 编辑:程序博客网 时间:2024/06/15 17:21

题目描述


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.

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.

解题思路


在二维数组中寻找字符串的匹配,使用回溯+贪心算法解决:

isFound是构造的辅助函数,主要用来检测是否发现了下一个搜索点
还需要稍微注意一下边界值的判断:搜索到最后一个字符怎么办?没有搜索点怎么办?(这里我采取的方法是都丢进isFound函数解决)

class Solution {public:    bool exist(vector<vector<char>>& board, string word) {        if(board.empty()||word.size()==0) return false;        m=board.size(),n=board[0].size();        //char *w=&word[0];        for(int i=0;i<m;i++)          for(int j=0;j<n;j++){              if(isFound(board,word.c_str(),i,j)) return true;          }          return false;    }    bool isFound(vector<vector<char> > &board, const char* w, int x, int y){        if(x>=m||x<0||y<0||y>=n||*w!=board[x][y])  return false;        if(*(w+1)=='\0')  return true;        char tmp=board[x][y];        board[x][y]='\0';        if(isFound(board,w+1,x+1,y)||isFound(board,w+1,x-1,y)||isFound(board,w+1,x,y+1)||isFound(board,w+1,x,y-1))            return true;        board[x][y]=tmp;        return false;    }    private:     int m,n;};