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
.
题目如上,大意是给出一个字符矩阵,然后给定一个字符串,看能不能从这个矩阵中找到这个字符串序列。就像是玩贪吃蛇一样,从第一个字符开始,上下左右移动,看能不能找到整个序列。且矩阵中的字符不能重用。一个很简单的思路就是dfs。代码如下,使用了回溯,如果不回溯的话可以直接选择传参也是可以通过的,但是运行效率慢了3倍。
#include<iostream>
#include<string>
#include<vector>
using namespace std;
class Solution {
public:
string w;
int row,col,l;
bool exist(vector<vector<char>>& board, string word) {
if(board.size()==0)
{
if(word=="")
return 1;
else
return 0;
}
w=word;
row=board.size();
col=board[0].size();
l=word.length();
for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++)
{
if(board[i][j]==word[0])
if(dfs(board,0,i,j))
return true;
}
}
return false;
}
bool dfs(vector<vector<char>>& board,int current,int r,int c)
{
if(l==current+1)
return true;
char s=board[r][c];
board[r][c]='0';
//cout<<r<<c<<endl;
if(r+1<row&&board[r+1][c]==w[current+1])
{
if(dfs(board,current+1,r+1,c))
return true;
}
if(r-1>=0&&board[r-1][c]==w[current+1])
{
if(dfs(board,current+1,r-1,c))
return true;
}
if(c-1>=0&&board[r][c-1]==w[current+1])
{
if(dfs(board,current+1,r,c-1))
return true;
}
if(c+1<col&&board[r][c+1]==w[current+1])
{
if(dfs(board,current+1,r,c+1))
return true;
}
board[r][c]=s;
return false;
}
};