[LeetCode]Word Search --

来源:互联网 发布:苹果手机频谱仪软件 编辑:程序博客网 时间:2024/06/06 19:35

题目:
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.

Given board =

[
[“ABCE”],
[“SFCS”],
[“ADEE”]
]
word = “ABCCED”, -> returns true,
word = “SEE”, -> returns true,
word = “ABCB”, -> returns false.
题目分析:”be constructed from letters of sequentially adjacent cell”应该是说单词可以在它能接触到的邻居字符连续的构成。说的什么鬼,还是举例子吧。board:[“ab”,’cd’] word: “abcd” ->expected false . 因为 在矩阵board中,b、c是不相邻的。

代码实现

#include <iostream>#include<vector>#include<string>using namespace std;/*Problem:Word SearchGiven 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 horizontallyor vertically neighboring. The same letter cell may not be used more than once.*/    bool isFound(vector<vector<char>> &board,const char* w,int i,int j){        int m=board.size();int n=board[0].size();        if(i<0||j<0||i>=m||j>=n||board[i][j]=='\0'||*w!=board[i][j])            return false;        if(*(w+1)=='\0')return true;        char t=board[i][j];        board[i][j]='\0';        if(isFound(board,w+1,i-1,j)||isFound(board,w+1,i+1,j)||isFound(board,w+1,i,j-1)||isFound(board,w+1,i,j+1))            return true;        board[i][j]=t;        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<n;i++){            for(int j=0;j<m;j++){                if(isFound(board,word.c_str(),i,j))                    return true;            }        }        return false;    }int main(){    vector<vector<char>> board={{'A','B','C','E'},{'S','F','C','S'},{'A','D','E','E'}};    string word="CCBA";    bool res=exist(board,word);    cout << "Hello world!" << res<<endl;    return 0;}
0 0
原创粉丝点击