Leetcode Word Search 相关代码,本代码使用dfs(广度优先搜索)算法,以下给出代码示例,以及相关测试:
#include<vector>
#include<iostream>
#include<string>
using namespace std;
/*
* We use the DFS algorithm complete this problem.
*/
class Solution {
public:
bool exist(vector<vector<char> >& board, string word) {
// Save the Row and Col to reduce the cost by invoke the vector::size()
int Row = board.size();
int Col = 0;
if (Row > 0) {
Col = board[0].size();
}
for (int i = 0; i < Row; i ++) {
for (int j = 0; j < Col; j ++) {
if (search(board, word, 0, i, j, Row, Col)) {
return true;
}
}
}
return false;
}
// use recursive and dfs to solve this problem
bool search(vector<vector<char> >& board, string& word, int pos, int pos_x, \
int pos_y, int Row, int Col) {
if (word.length() == pos) {
return true;
} else {
if (pos_x < 0 || pos_x >= Row || pos_y < 0 || pos_y >= Col \
|| board[pos_x][pos_y] == ' ') {
return false;
}
if (board[pos_x][pos_y] == word[pos]) {
char temp = board[pos_x][pos_y];
board[pos_x][pos_y] = ' ';
bool re = search(board, word, pos + 1, pos_x + 1, pos_y, Row, Col) || \
search(board, word, pos + 1, pos_x - 1, pos_y, Row, Col) || \
search(board, word, pos + 1, pos_x, pos_y + 1, Row, Col) || \
search(board, word, pos + 1, pos_x, pos_y - 1, Row, Col);
if (re) {
return true;
} else {
board[pos_x][pos_y] = temp;
}
}
return false;
}
}
};
int main(int argc, char* argv[]) {
vector<vector<char> > test;
vector<char> ele1(2, 'a');
vector<char> ele2(2, 'b');
test.push_back(ele1);
test.push_back(ele2);
Solution so;
bool re = so.exist(test, "abba");
cout<<"result: "<<re<<endl;
return 0;
}