[华为机试真题]66.单词搜索

简介:

题目

这里写图片描述

代码

/*---------------------------------------
*   日期:2015-07-06
*   作者:SJF0115
*   题目:WordSearch
*   来源:华为机试真题
-----------------------------------------*/
#include <iostream>
#include <string>
#include <vector>
#include <stack>
#include <algorithm>
using namespace std;


bool DFS(vector<vector<char> > &board,string word,int index,int x,int y,vector<vector<bool> > &visited){
    // 找到目标
    if(index == word.size()){
        return true;
    }//if
    int m = board.size();
    if(m == 0){
        return false;
    }//if
    int n = board[0].size();
    // 出界
    if(x < 0 || x >= m || y < 0 || y > n){
        return false;
    }//if
    // 已访问过
    if(visited[x][y]){
        return false;
    }//if
    // 不相等 剪枝
    if(board[x][y] != word[index]){
        return false;
    }//if
    visited[x][y] = true;
    // left
    bool left = DFS(board,word,index+1,x,y-1,visited);
    // right
    bool right = DFS(board,word,index+1,x,y+1,visited);
    // up
    bool up = DFS(board,word,index+1,x-1,y,visited);
    // bottom
    bool bottom = DFS(board,word,index+1,x+1,y,visited);
    visited[x][y] = false;
    // 四个方向 任意方向找到一个即可
    return left || right || up || bottom;
}
// 单词搜索
bool WordSearch(vector<vector<char> > &board,int m,int n,string word){
    if(n <= 0 || m <= 0 || board.empty()){
        return false;
    }//if
    // 判断是否已经访问过
    vector<vector<bool> > visited(m,vector<bool>(n,false));
    // 搜索
    for(int i = 0;i < m;++i){
        for(int j = 0;j < n;++j){
            if(board[i][j] == word[0]){
                // 以board[i][j]为起点开始搜索
                if(DFS(board,word,0,i,j,visited)){
                    return true;
                }//if
            }//if
        }//for
    }//for
    return false;
}

int main(){
    int m,n;
    string word;
    //freopen("C:\\Users\\Administrator\\Desktop\\acm.txt","r",stdin);
    while(cin>>m>>n>>word){
        vector<vector<char> > board(m,vector<char>(n,0));
        // 输入
        for(int i = 0;i < m;++i){
            for(int j = 0;j < n;++j){
                cin>>board[i][j];
            }//for
        }//for
        // 搜索
        bool result = WordSearch(board,m,n,word);
        if(result){
            cout<<"YES"<<endl;
        }//if
        else{
            cout<<"NO"<<endl;
        }//else
    }//while
    return 0;
}
目录
相关文章
|
3月前
leetcode-212:单词搜索 II
leetcode-212:单词搜索 II
22 0
|
3月前
leetcode-79:单词搜索
leetcode-79:单词搜索
20 0
|
4月前
|
存储 算法 vr&ar
☆打卡算法☆LeetCode 212. 单词搜索 II 算法解析
☆打卡算法☆LeetCode 212. 单词搜索 II 算法解析
☆打卡算法☆LeetCode 212. 单词搜索 II 算法解析
|
自然语言处理
LeetCode每日一题——745. 前缀和后缀搜索
设计一个包含一些单词的特殊词典,并能够通过前缀和后缀来检索单词。
53 0
|
算法 Java C++
LeetCode(算法)- 79. 单词搜索
LeetCode(算法)- 79. 单词搜索
66 0
|
算法
重温算法之单词搜索
对于回溯算法大家都不陌生,为此还有题友写成了回溯算法的模板,只要按模板套题都能灵活解题,算是开辟了一种做题的方式吧,有的算法题还是很磨人的。
113 0
重温算法之单词搜索
|
算法 前端开发 程序员
「LeetCode」79-单词搜索⚡️
「LeetCode」79-单词搜索⚡️
107 0
「LeetCode」79-单词搜索⚡️
☆打卡算法☆LeetCode 79、单词搜索 算法解析
“给定一个二维数组和一个单词,如果单词存在网格中返回true,否则返回false。”