您的位置:首页 > 其它

leetcode 079 —— Word Search

2015-08-03 12:10 399 查看
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
.
思路: 思路,用一个矩阵记录被使用的单词,但是代码跑了44ms,还有优化的空间

class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {
bool judge = false;
int level = 0;
vector<vector<bool>> record(board.size(), vector<bool>(board[0].size(), false));
for (int m = 0; m <board.size(); m++){
for (int n = 0; n <board[0].size(); n++){
if (board[m]
== word[0]){
record[m]
= true;
level = 1;
scan(m, n, judge, level, word, record, board);
if (judge) return judge;
record[m]
= false;
}
}
}
return judge;
}
void scan(int i, int j, bool &judge,int &level, string &word,vector<vector<bool>> &record,vector<vector<char>> &board){
if (level== word.size()){
judge = true;
return;
}
if (i + 1 < board.size() && !record[i + 1][j] && board[i + 1][j] == word[level]){ //往右
record[i + 1][j] = true;
level++;
scan(i + 1, j, judge, level, word, record, board);
level--;
if (judge) return;
record[i + 1][j] = false;
}
if (i - 1 >= 0 && !record[i - 1][j] && board[i - 1][j] == word[level]){ //往左
record[i - 1][j] = true;
level++;
scan(i - 1, j, judge, level, word, record, board);
level--;
if (judge) return;
record[i - 1][j] = false;
}
if (j + 1 < board[0].size() && !record[i][j + 1] && board[i][j+1] == word[level]){ //往下
record[i][j+1] = true;
level++;
scan(i, j + 1, judge, level, word, record, board);
level--;
if (judge) return;
record[i][j+1] = false;
}
if (j - 1 >= 0 && !record[i][j - 1] && board[i][j-1] == word[level]){ //往上
record[i][j-1] = true;
level++;
scan(i , j-1, judge, level, word, record, board);
if (judge) return;
level--;
record[i][j-1] = false;
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: