首页 > 其他 > 详细

Word Search

时间:2014-07-07 17:30:08      阅读:307      评论: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 =

[
  ["ABCE"],
  ["SFCS"],
  ["ADEE"]
]

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

思路:递归搜索,即递归搜索某一符合条件的字符的上、下、左、右四个方向,直到找到最后满足条件。

class Solution {
public:
    bool search(vector<vector<char> > &board,string &word,vector<vector<bool> > &visited,int i,int j,int index)
    {
        if(index==word.size())
            return true;
        //up
        if(i-1>=0 && board[i-1][j]==word[index] && visited[i-1][j]==false)
        {
            visited[i-1][j]=true;//已经访问
            if(search(board,word,visited,i-1,j,index+1))
                return true;
            visited[i-1][j]=false;
        }
        //down
        if(i+1<board.size() && board[i+1][j]==word[index] && visited[i+1][j]==false)
        {
            visited[i+1][j]=true;//已经访问
            if(search(board,word,visited,i+1,j,index+1))
                return true;
            visited[i+1][j]=false;
        }
        //left
        if(j-1>=0 && board[i][j-1]==word[index] && visited[i][j-1]==false)
        {
            visited[i][j-1]=true;//已经访问
            if(search(board,word,visited,i,j-1,index+1))
                return true;
            visited[i][j-1]=false;
        }
        //right
        if(j+1<board[0].size() && board[i][j+1]==word[index] && visited[i][j+1]==false)
        {
            visited[i][j+1]=true;//已经访问
            if(search(board,word,visited,i,j+1,index+1))
                return true;
            visited[i][j+1]=false;
        }
        return false;
    }
    bool exist(vector<vector<char> > &board, string word) {
        int n=board.size();
        if(n<0)
            return false;
        int m=board[0].size();
        for(int i=0;i<board.size();i++)
        {
            for(int j=0;j<m;j++)
            {
                if(board[i][j]==word[0])
                {
                    vector<vector<bool> >visited(n,vector<bool>(m,false));
                    visited[i][j]=true;
                    if(search(board,word,visited,i,j,1))
                        return true;
                }
            }
        }
        return false;
    }
};

 

Word Search,布布扣,bubuko.com

Word Search

原文:http://www.cnblogs.com/awy-blog/p/3813597.html

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