这道题题目意思理解错了,以为是向那种岛的形状,没想到题目的意思是dfs那种一条路走到黑,我最后想不出来去看题解。。看完题解后原地爆炸
先把做错的贴了,AC的在下面(这里想的是用bfs来做像岛的那种形状,遇到的问题是例如一个字符分布在两条路径的两端,但是在计数时先走的路径用完了unorder_map里的值,所以会导致一旦有分支且分支的值出现在word里,那么直接导致错误,暂时不知道怎么解决
class Solution {
public:
int steped[10000];
int dir[4][2]{ {1,0},{-1,0},{0,1},{0,-1} };
struct pos {
int x;
int y;
pos(int i, int j) :x(i), y(j) {}
};
void mark_step(int width, int i, int j) {
steped[i*width + j] = 1;
}
bool is_steped(int width, int i, int j) {
return (bool)steped[i*width + j];
}
bool exist(vector<vector<char>>& board, string word) {
memset(steped, 0, sizeof(steped));
unordered_map<char, int>word_map;
for (int i = 0; i < word.length(); ++i)++word_map[word[i]];
int width = board[0].size();
int n = board.size();
int k_Cnt = word.length();
int Cnt = 0;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < width; ++j) {
if (is_steped(width, i, j))continue;
unordered_map<char, int>current_map = word_map;
queue<pos>q;
pos current_p(i, j);
q.push(current_p);
Cnt = 0;
while (!q.empty()) {
current_p = q.front();
q.pop();
for (int k = 0; k < 4; ++k) {
int temp_x = current_p.x + dir[k][0];
int temp_y = current_p.y + dir[k][1];
if (temp_x > 0 && temp_x < n&&temp_y>0 && temp_y < width&&
!is_steped(width,temp_x,temp_y)) {
mark_step(width, temp_x, temp_y);
if (current_map[board[temp_x][temp_y]] > 0) {
pos temp(temp_x, temp_y);
q.push(temp);
++Cnt;
--current_map[board[temp_x][temp_y]];
if (Cnt == k_Cnt)return true;
}
}
}
}
}
}
return false;
}
};
AC Code 就是最普通的dfs
class Solution {
public:
int step[1000][1000];
int dir[4][2] = { {0,1},{0,-1},{1,0},{-1,0} };
bool dfs(vector<vector<char>>& board,int current_i,int current_j,int pos,string word) {
if (pos == word.length()-1)return true;
for (int k = 0; k < 4; ++k) {
int temp_x = current_i + dir[k][0];
int temp_y = current_j + dir[k][1];
if (temp_x >= 0 && temp_y >= 0 && temp_x < board.size() && temp_y < board[0].size() &&
!step[temp_x][temp_y]) {
if (word[pos + 1] == board[temp_x][temp_y]) {
step[temp_x][temp_y] = 1;
if (dfs(board, temp_x, temp_y, pos + 1, word))return true;
step[temp_x][temp_y] = 0;
}
}
}
return false;
}
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 (word[0] != board[i][j])continue;
memset(step, 0, sizeof(step));
step[i][j] = 1;
if(dfs(board, i, j, 0, word))return true;
}
}
return false;
}
};