您的位置:首页 > 其它

Leetcode 79:Word Search

2017-10-18 11:08 375 查看

题目链接:

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