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.
同学们把leetcode刷了一遍又一遍~
class Solution {
public:
bool exist(vector<vector<char> > &board, string word) {
int n = board.size();
if (n == 0) return false;
int m = board[0].size();
set<pair<int,int> >s;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (check(board, word, i, j, 0, s) == true) return true;
}
}
return false;
}
bool check(vector<vector<char> >&a, string& w, int x, int y, int cnt, set<pair<int,int> >&s) {
if (cnt == w.size()) return true;
if (x >= a.size() || x < 0 || y >= a[0].size() || y < 0) return false;
if (s.count(make_pair(x,y)) > 0)return false;
if (w[cnt] != a[x][y]) return false;
s.insert(make_pair(x,y));
int dx[] = {0,0,1,-1};
int dy[] = {1,-1,0,0};
for (int i = 0; i < 4; i++) {
if (check(a, w, x+dx[i], y+dy[i], cnt+1, s) == true) return true;
}
s.erase(make_pair(x,y));
return false;
}
};

本文探讨了在二维网格中查找指定单词的方法,通过相邻单元格构建单词,且不重复使用同一单元格。
382

被折叠的 条评论
为什么被折叠?



