# LeetCode 79 Word Search

·  阅读 62

### 思路

1. 使用map记录哪些位置的元素已经使用过。一种比较好的做法是，在使用该位置的元素时，将该位置的元素修改为'\0'。此路不通，再改回来。

2. word传参使用char *更好，避免拷贝。

### 代码

``````class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {

for (int i = 0; i < board.size(); ++i) {
for (int j = 0; j < board[0].size(); ++j) {
if (!alreadyUse[i][j] && board[i][j] == word[0] && search(board, word.substr(1), alreadyUse, i , j))
return true;
}
}

return false;
}

bool search(vector<vector<char>> &board, string word, vector<vector<bool>> &alreadyUse, int x, int y) {
if (word.empty()) return true;

bool up = false, down = false, left = false, right = false;

if (x > 0 && !alreadyUse[x-1][y] && board[x-1][y] == word[0])
up = search(board, word.substr(1), alreadyUse, x-1, y);
if (!up && x < board.size() - 1 && !alreadyUse[x+1][y] && board[x+1][y] == word[0])
down = search(board, word.substr(1), alreadyUse, x+1, y);
if (!up && !down && y > 0 && !alreadyUse[x][y-1] && board[x][y-1] == word[0])
left = search(board, word.substr(1), alreadyUse, x, y-1);
if (!up && !down && !left && y < board[0].size() - 1 && !alreadyUse[x][y+1] && board[x][y+1] == word[0])
right = search(board, word.substr(1), alreadyUse, x, y+1);

if (up || down || left || right) return true;