題目鏈接:
https://leetcode.com/problems/word-search/description/
描述
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 =
word = “ABCCED”, -> returns true,
word = “SEE”, -> returns true,
word = “ABCB”, -> returns false.
算法思想:
深度搜索,剛開始矇頭寫深度搜索,使得有兩個測試用例超時,後來改進,但是在寫代碼時出現了一個小bug,將兩個語句順序調換了,調試了一兩個小時,沒誰了。。。。。。
AC源代碼
class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {
r = board.size(), c = board[0].size();
int i, j;
for ( i = 0; i < r; i++)
{
for ( j = 0; j < c; j++)
{
if (DFS(board, word, i, j, 0))
return true;
}
}
return false;
}
private:
int r, c;
bool DFS(vector<vector<char>>& board, string str, int x, int y, int k)
{
if (x < 0 || x >= r || y >= c || y < 0 || board[x][y] != str[k] || !board[x][y]) return false;
if (k == str.length() - 1)
{
return true;
}
char ch = board[x][y];
board[x][y] = 0;
if (DFS(board, str, x, y + 1, k + 1) || DFS(board, str, x + 1, y, k + 1) || DFS(board, str, x, y - 1, k + 1) || DFS(board, str, x - 1, y, k + 1))
return true;
board[x][y] = ch;
return false;
}
};
超時源代碼
class Solution {
public:
int ko = 0;
vector<vector<char>> board;
void DFS(vector<vector<char>>& board,string str, int x, int y,int k)
{
//cout << x << " " << y << " " << board[x][y] << endl;
if (board[x][y] != str[k] || !board[x][y]) return;
if (k == str.length() - 1)
{
ko = 1;
return;
}
char ch = board[x][y];
board[x][y] = 0;
int num = k;
k++;
if (y < board[0].size() - 1)
{
DFS(board, str, x, y + 1, k);
}
if (x < board.size() - 1)
{
DFS(board, str, x + 1, y, k);
}
if (y >= 1)
{
DFS(board, str, x, y - 1, k);
}
if (x >= 1)
{
DFS(board, str, x - 1, y, k);
}
k = num;
board[x][y] = ch;
}
bool exist(vector<vector<char>>& board, string word) {
vector<vector<char>> newboard;
for (int i = 0; i < board.size(); i++)
{
for (int j = 0; j < board[0].size(); j++)
{
newboard = board;
DFS(newboard, word, i, j, 0);
if(ko)
break;
}
if(ko)
break;
}
cout << ko << endl;
return ko;
}
};