Word Search

来源:互联网 发布:淘宝女装店铺描述范文 编辑:程序博客网 时间:2024/06/05 20:13

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搜索+回溯。

设置dir[4][2]作为移动方向。

int maxdep, m, n;int dir[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};bool dfs(string word, int dep, vector<vector<char> > &board, int x, int y, vector<vector<bool> > &visit){    if (dep == maxdep)        return true;    for (int i = 0; i < 4; i++)    {        int xx = x + dir[i][0];        int yy = y + dir[i][1];        if (xx >= 0 && xx < m && yy >= 0 && yy < n && board[xx][yy] == word[dep] && !visit[xx][yy])        {            visit[xx][yy] = true;            if (dfs(word, dep+1, board, xx, yy, visit))                return true;            visit[xx][yy] = false;        }    }}bool exist(vector<vector<char> > &board, string word){    if (word.size()==0)        return true;    if (board.size()==0)        return false;    maxdep = word.size();    m = board.size();    n = board[0].size();    vector<vector<bool> > visit(m, vector<bool>(n, false));    for (int i = 0; i < m; i++)    {        for (int j = 0; j < n; j++)        {            if (word[0] == board[i][j])            {                visit[i][j] = true;                if (dfs(word, 1, board, i, j, visit)) return true;                visit[i][j] = false;            }        }    }    return false;}


0 0
原创粉丝点击