[leetcode]Word Search

来源:互联网 发布:ipadpro绘画软件推荐 编辑:程序博客网 时间:2024/06/06 01:43

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 =

[
[“ABCE”],
[“SFCS”],
[“ADEE”]
]

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

思路:
dfs的方法,跟解迷宫问题很相似。
1)找到开始的入口,这里就是找到和值word[0]一样的位置
2)开始递归查找,word[1],word[2]….word[word.size()-1],和解迷宫题一样,这里是要求相邻的格子,所以上下左右四个方向寻找合适的解。
3)如果cur=word.size(),代表已经找到了这个单词的所有字符,返回成功。算法结束。

class Solution {public:    bool visited[100][100];    int  step[4][2];    void dfs(int x,int y,int cur,int len,string &word,vector<vector<char> > &board,bool &flag){        if(flag)  return;        if(cur == len) {            flag = true;            return;        }        for(int i=0;i<4;i++){            int tx = x + step[i][0];            int ty = y + step[i][1];            if(tx >=0 && tx < board.size() && ty >= 0 && ty < board[0].size() && (visited[tx][ty] == false) && board[tx][ty] == word[cur]){                visited[tx][ty] = true;                dfs(tx,ty,cur+1,len,word,board,flag);                visited[tx][ty] = false;            }        }    }    void init(){        memset(visited,false,sizeof(visited));        step[0][0] = 1;        step[0][1] = 0;        step[1][0] = -1;        step[1][1] = 0;        step[2][0] = 0;        step[2][1] = 1;        step[3][0] = 0;        step[3][1] = -1;    }    bool exist(vector<vector<char> > &board, string word) {        int i,j;        if (word.size() == 0)  return true;        init();        for(i=0; i<board.size();i++){            for(j=0;j<board[0].size();j++){                if(board[i][j]==word[0]){                    bool flag = false;                    visited[i][j] = true;                    dfs(i,j,1,word.size(),word,board,flag);                    if(flag) return true;                    visited[i][j] = false;                }            }            }        return false;    }};
1 0