您的位置:首页 > 其它

LeetCode: Word Search

2014-11-03 14:05 274 查看
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 exist(vector<vector<char> > &board, string word) {
if(word.size() == 0)
return true;
for(int i = 0; i < board.size(); i++)
for(int j = 0; j < board[i].size(); j++)
{
if(dfs(0, board, word, i, j))
return true;
}
return false;
}
bool dfs(int index, vector<vector<char> > &board, string word, int x, int y)
{
if(board[x][y] != word[index])
return false;
else
{
if(index == word.size() - 1)
return true;
char store = board[x][y];
if(x-1 >= 0)
{
board[x][y] = '#';
if(dfs(index+1, board, word, x-1, y))
return true;
board[x][y] = store;
}
if(x+1 < board.size())
{
board[x][y] = '#';
if(dfs(index+1, board, word, x+1, y))
return true;
board[x][y] = store;
}
if(y-1 >= 0)
{
board[x][y] = '#';
if(dfs(index+1, board, word, x, y-1))
return true;
board[x][y] = store;
}
if(y+1 < board[0].size())
{
board[x][y] = '#';
if(dfs(index+1, board, word, x, y+1))
return true;
board[x][y] = store;
}
return false;
}

}
};


Round 2:

class Solution {
public:
bool exist(vector<vector<char> > &board, string word) {
if(board.size() == 0)
return false;
int sizeX = board.size();
int sizeY = board[0].size();
for(int i = 0; i < sizeX; i++)
for(int j = 0; j < sizeY; j++)
{
if(dfs(i, j, word, board, 0))
return true;
}
return false;
}
private:
bool dfs(int x, int y, string target, vector<vector<char> > &board, int index)
{
if(board[x][y] != target[index])
return false;
if(index == target.size()-1)
return true;
if(x-1 >= 0 && board[x-1][y] == target[index+1])
{
char temp = board[x][y];
board[x][y] = '#';
if(dfs(x-1, y, target, board, index+1))
{
return true;
}
board[x][y] = temp;
}
if(y-1 >= 0 && board[x][y-1] == target[index+1])
{
char temp = board[x][y];
board[x][y] = '#';
if(dfs(x, y-1, target, board, index+1))
{
return true;
}
board[x][y] = temp;
}
if(y+1 < board[0].size() && board[x][y+1] == target[index+1])
{
char temp = board[x][y];
board[x][y] = '#';
if(dfs(x, y+1, target, board, index+1))
{
return true;
}
board[x][y] = temp;
}
if(x+1 < board.size() && board[x+1][y] == target[index+1])
{
char temp = board[x][y];
board[x][y] = '#';
if(dfs(x+1, y, target, board, index+1))
{
return true;
}
board[x][y] = temp;
}
return false;

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: