首页 > 其他 > 详细

[leetcode-79-Word Search]

时间:2017-04-23 11:46:33      阅读:124      评论:0      收藏:0      [点我收藏+]

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.

思路:

深度优先遍历。

bool dfs(vector< vector< char> >& board, string word,int row ,int col ,int start,int m,int n,int length)
{
    char curChar = board[row][col];
    bool res = false;

    if(curChar != word[start]) return false;
    if(start == length - 1) return true;

    board[row][col] = *;
    if(row>0) res = dfs(board,word,row-1,col,start+1,m,n,length);
    if(!res && row < m-1) res = dfs(board,word,row+1,col,start+1,m,n,length);
    if(!res && col>0) res = dfs(board,word,row,col-1,start+1,m,n,length);
    if(!res && col<n-1) res = dfs(board,word,row,col+1,start+1,m,n,length);
    board[row][col] = curChar;

    return res;
}
bool exist(vector< vector< char> >& board, string word)
{
    int m = board.size() , n = board[0].size(), length = word.size();

    if( m && n && length)
    {
        for(int i = 0;i < m;i++)
        {
            for(int j =0;j<n;j++)
            {
                if(dfs(board,word,i,j,0,m,n,length))
                    return true;
            }
        }
    }
    return false;
}

 

[leetcode-79-Word Search]

原文:http://www.cnblogs.com/hellowooorld/p/6751970.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!