【LeetCode】BFS(共43题)

时间:2023-03-09 03:31:15
【LeetCode】BFS(共43题)

【101】Symmetric Tree

判断一棵树是不是对称。

题解:直接递归判断了,感觉和bfs没有什么强联系,当然如果你一定要用queue改写的话,勉强也能算bfs。

// 这个题目的重点是 比较对象是 左子树的左儿子和右子树的右儿子, 左子树的右儿子和右子树的左儿子。不要搞错。

// 直接中序遍历的话会有错的情况,最蠢的情况是数字标注改一改。。

 /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
// 这个题目的重点是 比较对象是 左子树的左儿子和右子树的右儿子, 左子树的右儿子和右子树的左儿子。不要搞错。
// 直接中序遍历的话会有错的情况,最蠢的情况是数字标注改一改。。
class Solution {
public:
bool isSymmetric(TreeNode* left, TreeNode* right) {
if (left == NULL && right == NULL) {return true;}
if (left == NULL || right == NULL) {return false;}
return (left->val == right->val) && isSymmetric(left->left, right->right) && isSymmetric(left->right, right->left);
}
bool isSymmetric(TreeNode* root) {
if (!root) {
return true;
}
return isSymmetric(root->left, root->right);
}
};

【102】Binary Tree Level Order Traversal

二叉树的层级遍历。

题解:两个队列直接遍历。

 /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> ans;
if (!root) {
return ans;
}
queue<TreeNode*> que1, que2;
que1.push(root);
while (!que1.empty()) {
vector<int> temp;
while (!que1.empty()) {
TreeNode* node = que1.front();
que1.pop();
temp.push_back(node->val);
if (node->left) {
que2.push(node->left);
}
if (node->right) {
que2.push(node->right);
}
}
ans.push_back(temp);
temp.clear();
swap(que1, que2);
}
return ans;
}
};

【103】Binary Tree Zigzag Level Order Traversal

二叉树的蛇形层级遍历。

题解:我是直接用了两个栈,当然,也可以直接层级遍历出结果然后reverse。

 /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
vector<vector<int>> ans;
if (!root) {return ans;}
stack<TreeNode*> st1, st2;
st1.push(root);
bool reverse = true;
while (!st1.empty()) {
vector<int> temp;
while (!st1.empty()) {
TreeNode* node = st1.top();
st1.pop();
temp.push_back(node->val);
if (reverse) {
if (node->left) {
st2.push(node->left);
}
if (node->right) {
st2.push(node->right);
}
} else {
if (node->right) {
st2.push(node->right);
}
if (node->left) {
st2.push(node->left);
}
}
}
ans.push_back(temp);
temp.clear();
swap(st1, st2);
reverse = - reverse;
}
return ans;
}
};

【107】Binary Tree Level Order Traversal II

二叉树从下往上的层级遍历

题解:我直接把层级遍历reverse了一下。

 /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> levelOrderBottom(TreeNode* root) {
vector<vector<int>> ans;
if (!root) {
return ans;
}
queue<TreeNode*> que1, que2;
que1.push(root);
while (!que1.empty()) {
vector<int> temp;
while (!que1.empty()) {
TreeNode* node = que1.front();
que1.pop();
temp.push_back(node->val);
if (node->left) {
que2.push(node->left);
}
if (node->right) {
que2.push(node->right);
}
}
ans.push_back(temp);
temp.clear();
swap(que1, que2);
}
reverse(ans.begin(), ans.end());
return ans;
}
};

【111】Minimum Depth of Binary Tree

返回一棵二叉树的最短的高度,最短的高度的定义是从根开始到没有左右儿子的叶子节点的最短的距离。

题解:直接bfs,判断出叶子节点就停止。

 /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int minDepth(TreeNode* root) {
int ans = ;
if (!root) {return ans;}
queue<TreeNode*> que, que2;
que.push(root);
bool finish = false;
while (!que.empty()) {
while (!que.empty()) {
TreeNode* node = que.front();
que.pop();
if (node == NULL) {continue;}
if (node->left == NULL && node->right == NULL) {
finish = true;
break;
} else {
que2.push(node->left);
que2.push(node->right);
}
}
ans++;
if (finish) {
break;
}
swap(que, que2);
}
return ans;
}
};

【126】Word Ladder II

题目和127题一样,区别在于这题要求返回全部最短路径。

题解:修改了一下127题的题解,在bfs的时候增加一个层次数组,把每层走过的单词都存起来,一旦找到了目标单词,回溯整个层级数组得到答案。

 class Solution {
public:
bool distance1(string& s, string& t) {
int n = s.size();
int dis = ;
for (int i = ; i < n; ++i) {
if (s[i] != t[i]) {
++dis;
}
if (dis >= ) { return false; }
}
return dis == ? true : false;
}
void dfs(vector<vector<string>>& ans, vector<string>& temp, string curWord, int level) {
if (temp.back() == beginW) {
ans.push_back(temp);
}
if (level == wordLevel.size()) { return; }
vector<string> list = wordLevel[level];
for (auto word : list) {
if (distance1(word, curWord)) {
temp.push_back(word);
dfs(ans, temp, word, level+);
temp.pop_back();
}
}
}
vector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList) {
vector<vector<string>> ans;
if (find(wordList.begin(), wordList.end(), endWord) == wordList.end()) {return ans;}
queue<string> que, que2;
set<string> st;
que.push(beginWord);
bool findAns = false;
while(!que.empty()) {
vector<string> temp;
while (!que.empty()) {
string str = que.front();
temp.push_back(str);
que.pop();
for (auto word : wordList) {
if (distance1(str, word) && st.find(word) == st.end()) {
if (word == endWord) {
findAns = true;
}
que2.push(word);
st.insert(word);
}
}
}
wordLevel.push_back(temp);
if (findAns) {
break;
}
swap(que, que2);
}
/*
printf("findAns = %d\n", findAns);
for (int i = 0; i < wordLevel.size(); ++i) {
for (int j = 0; j < wordLevel[j].size(); ++j) {
cout << wordLevel[i][j] << "";
}
cout << endl;
}
*/
if (findAns == false) { return ans; }
reverse(wordLevel.begin(), wordLevel.end());
beginW = beginWord, endW = endWord;
vector<string> temp;
temp.push_back(endW);
dfs(ans, temp, endW, );
for (int i = ; i < ans.size(); ++i) {
reverse(ans[i].begin(), ans[i].end());
}
return ans;
}
string beginW, endW;
vector<vector<string>> wordLevel;
};

【127】Word Ladder (2018年12月28日,第一次复习,ko)

给了一个初始单词和一个目标单词和一个单词字典,每次变换只能把当前单词变一个字母变成单词字典里面的一个词,问初始单词经过几次变换能变成目标单词。

题解:从初始单词开始,从字典里面找到能走一步的所有的单词放到队列里,然后遍历队列,直到找到目标单词,注意字典中所有的单词只能用一次,不然可能有环,就死循环了。

 class Solution {
public:
bool distance1(string& s, string& t) {
int n = s.size();
int dis = ;
for (int i = ; i < n; ++i) {
if (s[i] != t[i]) {
++dis;
}
if (dis >= ) { return false; }
}
return dis == ? true : false;
} int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
int ans = ;
if (find(wordList.begin(), wordList.end(), endWord) == wordList.end()) {return ans;}
queue<string> que, que2;
set<string> st;
que.push(beginWord);
ans = ;
bool findAns = false;
while(!que.empty()) {
while (!que.empty()) {
string str = que.front();
que.pop();
for (auto word : wordList) {
if (distance1(str, word) && st.find(word) == st.end()) {
if (word == endWord) {
findAns = true;
break;
}
que2.push(word);
st.insert(word);
}
}
if (findAns) {
break;
}
}
ans++;
if (findAns) {
break;
}
swap(que, que2);
}
return findAns ? ans : ;
}
};

2018年12月28日补充,直接bfs就行了,现在写的很快。

 class Solution {
public:
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
set<string> st(wordList.begin(), wordList.end());
if (st.find(endWord) == st.end()) {return ;}
const int n = wordList.size();
int step = ;
vector<int> visit(n, );
queue<string> que;
que.push(beginWord);
while (!que.empty()) {
const int size = que.size();
step++;
for (int i = ; i < size; ++i) {
string cur = que.front(); que.pop();
for (int k = ; k < n; ++k) {
if (visit[k]) {continue;}
if (diff(cur, wordList[k]) == ) {
visit[k] = ;
que.push(wordList[k]);
if (wordList[k] == endWord) {
return step + ;
}
}
}
}
}
return ;
}
int diff(string s1, string s2) {
if (s1.size() != s2.size()) {return -;}
int cnt = ;
for (int i = ; i < s1.size(); ++i) {
if (s1[i] != s2[i]) {
++cnt;
}
}
return cnt;
}
};

2018/12/28

【130】Surrounded Regions

给了一个矩阵,有字母 ‘O’ 和 ‘X’ 组成,要求把由X包围的所有O都反转成X。 跟边界上的O相连的O就不算被X包围。

题解:直接dfs, floodfill。

 class Solution {
public:
int dirx[] = {-, , , };
int diry[] = {, -, , };
void solve(vector<vector<char>>& board) {
n = board.size();
if (n == ) {return;}
m = board[].size();
if (m == ) {return;}
//mat 0: 没有访问过的,2:和边界上的O相连的
vector<vector<int>> mat(n, vector<int>(m, ));
for (int i = ; i < n; ++i) {
if (mat[i][] == && board[i][] == 'O') {
floodfill(board, mat, i, );
}
if (mat[i][m-] == && board[i][m-] == 'O') {
floodfill(board, mat, i, m -);
}
}
for (int j = ; j < m; ++j) {
if (mat[][j] == && board[][j] == 'O') {
floodfill(board, mat, , j);
}
if (mat[n-][j] == && board[n-][j] == 'O') {
floodfill(board, mat, n-, j);
}
} for (int i = ; i < n; ++i) {
for (int j = ; j < m; ++j) {
board[i][j] = mat[i][j] == ? 'O' : 'X';
}
}
return; }
void floodfill(vector<vector<char>>& board, vector<vector<int>>& mat, int x, int y) {
mat[x][y] = ;
for (int i = ; i < ; ++i) {
int newx = x + dirx[i], newy = y + diry[i];
if (newx >= && newx < n && newy >= && newy < m && board[newx][newy] == 'O' && mat[newx][newy] == ) {
floodfill(board, mat, newx, newy);
}
}
}
int n, m;
};

【133】Clone Graph 

题目要求克隆一张图,返回这张图的深拷贝。

题解:这题纠结比较久,主要是因为指针不熟了,为啥p2指针一定要在外面定义,要解决这个问题。这题需要review。

 /**
* Definition for undirected graph.
* struct UndirectedGraphNode {
* int label;
* vector<UndirectedGraphNode *> neighbors;
* UndirectedGraphNode(int x) : label(x) {};
* };
*/
class Solution {
public:
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
if (!node) {return node;}
queue<UndirectedGraphNode *> que;
que.push(node);
unordered_map<UndirectedGraphNode *, UndirectedGraphNode *> mp; UndirectedGraphNode *ans = new UndirectedGraphNode(node->label);
mp[node] = ans;
UndirectedGraphNode* p2 = ans; while (!que.empty()) {
UndirectedGraphNode *oriNode = que.front();
p2 = mp[oriNode];
que.pop(); vector<UndirectedGraphNode *> nei = oriNode->neighbors;
for (int i = ; i < nei.size(); ++i) {
if (mp.find(nei[i]) != mp.end()) {
p2->neighbors.push_back(mp[nei[i]]);
continue;
}
que.push(nei[i]);
UndirectedGraphNode * newNode = new UndirectedGraphNode(nei[i]->label);
mp[nei[i]] = newNode;
p2->neighbors.push_back(newNode);
} }
return ans;
}
};

【199】Binary Tree Right Side View

一棵二叉树,返回从右看能看到的数值,(只能看到每层最右的值),从上到下返回一个数组。

题解:还是层级遍历的变种。一次过了。

 /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> rightSideView(TreeNode* root) {
vector<int> ans;
if (!root) { return ans; }
queue<TreeNode*> que, que2;
que.push(root);
while (!que.empty()) {
while (!que.empty()) {
TreeNode* node = que.front();
que.pop();
if (que.size() == ) {
ans.push_back(node->val);
}
if (node->left) { que2.push(node->left); }
if (node->right) { que2.push(node->right); }
}
swap(que, que2);
}
return ans;
}
};

【200】Number of Islands

给了一个01矩阵,1的连通块代表一个岛,0代表水,问一共有几个岛。 (连通是四连通)

题解:直接dfs

 class Solution {
public:
int numIslands(vector<vector<char>>& grid) {
n = grid.size();
if (n == ) {return ;}
m = grid[].size();
if (m == ) {return ;}
vector<vector<int>> vis(n, vector<int>(m, ));
int ans = ;
for (int i = ; i < n; ++i) {
for (int j = ; j < m; ++j) {
if (grid[i][j] == '' && !vis[i][j]) {
dfs(grid, vis, i, j);
ans++;
}
}
}
return ans;
}
void dfs(const vector<vector<char>>& grid, vector<vector<int>>& vis, int x, int y) {
vis[x][y] = ;
for (int i = ; i < ; ++i) {
int newx = x + dirx[i], newy = y + diry[i];
if (newx >= && newx < n && newy >= && newy < m && !vis[newx][newy] && grid[newx][newy] == '') {
dfs(grid, vis, newx, newy);
}
}
} int n, m;
int dirx[] = {-, , , };
int diry[] = {, -, , }; };

【207】Course Schedule (2019年1月20日,topologic sort 的bfs形式)

给了n门课程,有些课程在修之前有前置课程,给出了这些前置限制,判断这些课程能否修完。

题解:直接拓扑排序。

 class Solution {
public:
bool dfs(const vector<vector<int>>& g, vector<int>& c, int u) {
c[u] = -;
for (int v = ; v < n; ++v) {
if (g[u][v]) {
if (c[v] < ) { return false; }
else if (!c[v] && !dfs(g, c, v)) {
return false;
}
}
}
c[u] = ;
topo[--t] = u;
return true;
}
bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {
vector<vector<int>> graph(numCourses, vector<int>(numCourses, ));
n = numCourses;
topo.resize(n);
t = n;
for (auto ele : prerequisites) {
int u = ele.first, v = ele.second;
graph[v][u] = ;
}
vector<int> c(n, );
for (int i = ; i < n; ++i) {
if (!c[i]) {
if (!dfs(graph, c, i)) {
return false;
}
}
}
/*
for (int i = 0; i < n; ++i) {
cout << topo[i] << " " ;
}
cout << endl;
*/
return true;
}
vector<int> topo;
int n, t;
};

2019年1月20日更新,topologic sort 的bfs形式更加好写。也更好理解。

我们先建图(邻接链表),然后去计算入度,然后把入度为0的点全都放进队列。开始bfs。注意这次bfs的循环结束条件是 for(int i = 0; i < n; ++i) 因为可能有环。

 class Solution {
public:
bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {
vector<vector<int>> g = initGraph(numCourses, prerequisites);
vector<int> degree = calDegree(g);
//find the vertex where degree == 0 and push them all into queue.
queue<int> que;
for (int i = ; i < degree.size(); ++i) {
if (degree[i] == ) {
que.push(i);
}
}
//start topologic sort
int idx = ;
for (; idx < numCourses; ++idx) {
if (que.empty()) {
return false;
}
int cur = que.front(); que.pop();
for (auto v : g[cur]) {
if (--degree[v] == ) {
que.push(v);
}
}
}
return true;
}
private:
vector<vector<int>> initGraph(int n, vector<pair<int, int>>& pre) {
vector<vector<int>> g(n, vector<int>());
for (auto e : pre) {
int start = e.second, end = e.first;
g[start].push_back(end);
}
return g;
}
vector<int> calDegree(vector<vector<int>>& g) {
vector<int> d(g.size(), );
const int n = g.size();
for (auto e : g) {
for (auto v : e) {
d[v]++;
}
}
return d;
}
};

【210】Course Schedule II (2019年1月20日,topologic sort 的bfs形式)

跟207一样,区别在于这题需要返回合法顺序。

题解:拓扑排序。

 class Solution {
public:
vector<int> findOrder(int numCourses, vector<pair<int, int>>& prerequisites) {
vector<vector<int>> graph(numCourses, vector<int>(numCourses, ));
n = numCourses;
topo.resize(n);
t = n;
for (auto ele : prerequisites) {
int u = ele.first, v = ele.second;
graph[v][u] = ;
}
vector<int> c(n, );
for (int i = ; i < n; ++i) {
if (!c[i]) {
if (!dfs(graph, c, i)) {
topo.clear();
return topo;
}
}
}
return topo;
}
bool dfs(const vector<vector<int>>& g, vector<int>& c, int u) {
c[u] = -;
for (int v = ; v < n; ++v) {
if (g[u][v]) {
if (c[v] < ) { return false; }
else if (!c[v] && !dfs(g, c, v)) {
return false;
}
}
}
c[u] = ;
topo[--t] = u;
return true;
}
vector<int> topo;
int n, t;
};

bfs 版本,特别简单。

 class Solution {
public:
vector<int> findOrder(int numCourses, vector<pair<int, int>>& prerequisites) {
vector<vector<int>> g = initGraph(numCourses, prerequisites);
vector<int> degree = calDegree(g);
vector<int> ret(numCourses, );
queue<int> que;
for (int i = ; i < degree.size(); ++i) {
if (degree[i] == ) {
que.push(i);
}
}
for (int i = ; i < numCourses; ++i) {
if (que.empty()) {
return vector<int>();
}
int cur = que.front(); que.pop();
ret[i] = cur;
for (auto e : g[cur]) {
if (--degree[e] == ) {
que.push(e);
}
}
}
return ret;
}
private:
vector<vector<int>> initGraph(int n, vector<pair<int, int>>& pre) {
vector<vector<int>> g(n, vector<int>());
for (auto e : pre) {
int start = e.second, end = e.first;
g[start].push_back(end);
}
return g;
}
vector<int> calDegree(vector<vector<int>>& g) {
vector<int> d(g.size(), );
const int n = g.size();
for (auto e : g) {
for (auto v : e) {
d[v]++;
}
}
return d;
}
};

【261】Graph Valid Tree

今天一会儿再看。

【279】Perfect Squares (2019年1月26日,谷歌tag复习)

给了一个正整数n, 求最少需要几个完全平方数(1, 4, 9, 16...)才能凑成和是n。

题解:看了小Q的题解,一个月之后写还是不会写。==

首先我们可以分析出来,因为1是个完全平方数,所以,n可以为任意正整数。只不过是最少怎么求的问题。 我们可以设置一个数组f,f[i]表示i最少需要几个完全平方数表示。

转移方程就是 f[m] = f[i + t*t] = f[i] +1。 我们用一个队列存储已经求出来的 m = i + t * t。

 class Solution {
public:
int numSquares(int n) {
vector<int> f(n+, -);
f[] = ;
queue<int> que;
que.push();
int m = ;
while (!que.empty()) {
int m = que.front();
que.pop();
for (int i = ; i * i + m <= n; ++i) {
if (f[i * i + m] == -) {
f[i*i+m] = f[m] + ;
que.push(i * i + m);
}
}
}
return f[n];
}
};

【286】Walls and Gates

一个矩阵,0代表大门,1代表障碍物,INF代表可以走的方块。要求返回这个矩阵,把可达的INF都换成离门的最短距离。

题解:类似于bfs,从大门开始一层一层标记INF。

 class Solution {
public:
void wallsAndGates(vector<vector<int>>& rooms) {
n = rooms.size();
if (n == ) { return; }
m = rooms[].size();
if (m == ) { return; } vector<pair<int, int>> begin;
for (int i = ; i < n; ++i) {
for (int j = ; j < m; ++j) {
if (rooms[i][j] == ) {
begin.push_back(make_pair(i, j));
}
}
}
for (auto b : begin) {
queue<pair<int, int>> que;
que.push(b);
for (; !que.empty(); que.pop()) {
pair<int, int> p = que.front();
int x = p.first, y = p.second;
for (int i = ; i < ; ++i) {
int newx = x + dirx[i], newy = y + diry[i];
if (newx >= && newx < n && newy >= && newy < m && rooms[newx][newy] != -) {
if (rooms[newx][newy] > rooms[x][y] + ) {
rooms[newx][newy] = rooms[x][y] + ;
que.push(make_pair(newx, newy));
}
}
}
}
}
return;
}
int n, m;
int dirx[] = {-, ,, };
int diry[] = {, -, , };
};

【301】Remove Invalid Parentheses

【310】Minimum Height Trees (算法群, 2018年11月13日)

给了一个有树特征的无向图,我们可以选任何一个结点作为树的根,然后这个图就可以变成一个有根树。在所有可能的有根树中,高度最小的就叫做 MHT, 写一个函数,要求返回这个图的 MHT 的所有的根。

题解:我一开始是直接暴力枚举每个结点作为树的根结点,然后用bfs求树的高度,比较最小值。时间复杂度是 O(N^2),超时了。 后来看了答案和群里,小Q的视频, 和discuss。有 O(N) 的解法。我们想象一下,我们每次可以去除一棵树的最外层的叶子结点(叶子结点的 degree 是 1),一层一层从外往里面剥洋葱,最后心里的结点就是所求树的根。

 class Solution {
public:
vector<int> findMinHeightTrees(int n, vector<pair<int, int>>& edges) {
if (n == ) {return vector<int>(); }
if (n == ) {return vector<int>{};}
vector<unordered_set<int>> edge(n, unordered_set<int>{});
vector<int> degree(n, );
//init graph
for (auto p : edges) {
edge[p.first].insert(p.second);
edge[p.second].insert(p.first);
degree[p.first]++, degree[p.second]++;
}
//bfs
queue<int> que;
//put all leaves nodes into queue
for (int i = ; i < n; ++i) {
if (degree[i] == ) {
que.push(i);
}
}
//bfs
vector<int> ret();
while (!que.empty()) {
int size = que.size();
ret.clear();
for (int i = ; i < size; ++i) {
int node = que.front(); que.pop();
ret.push_back(node);
for (auto adj : edge[node]) {
degree[adj]--;
if (degree[adj] == ) { //new leaves
que.push(adj);
}
}
}
}
return ret;
}
};

小Q的视频地址如下:https://www.bilibili.com/video/av13605504/?p=4  他用了dfs,我没怎么看懂,估计还是题量不够。唉。

然后discuss的链接:https://leetcode.com/problems/minimum-height-trees/discuss/76055/Share-some-thoughts

【317】Shortest Distance from All Buildings

【323】Number of Connected Components in an Undirected Graph

【407】Trapping Rain Water II

【417】Pacific Atlantic Water Flow

【429】N-ary Tree Level Order Traversal

【490】The Maze

给了一个二维矩阵做迷宫(0代表可以走, 1代表障碍物),一个小球,给了小球的开始位置和结束位置,问小球能否停止在结束位置。小球可以四个方向滚动,但是它只会碰到墙/障碍物才会停止,然后才能改变运动方向。

题解:可以dfs,也可以bfs。一开始觉得纠结的地方就是vis数组是小球经过这个位置就设置为1,还是只有小球停止在当前位置才能设置为1。后来看了别人的解法,只有小球在某个位置停止,才能把那个位置设置为1。

 class Solution {
public:
bool dfs(int cur_x, int cur_y) {
if (cur_x == des.first && cur_y == des.second) {
return true;
}
vis[cur_x][cur_y] = ;
for (int i = ; i < ; ++i) {
int new_x = cur_x + dirx[i], new_y = cur_y + diry[i];
while (new_x >= && new_x < n && new_y >= && new_y < m && mat[new_x][new_y] == ) {
new_x += dirx[i], new_y += diry[i];
}
new_x -= dirx[i], new_y -= diry[i];
if (!vis[new_x][new_y]) { //vis数组只在停留的地方有用。
bool temp = dfs(new_x, new_y);
if (temp) { return true; }
}
}
return false;
}
bool hasPath(vector<vector<int>>& maze, vector<int>& start, vector<int>& destination) {
st.first = start[], st.second = start[], des.first = destination[], des.second = destination[];
n = maze.size(), m = maze[].size();
vector<vector<int>> temp(n, vector<int>(m, ));
vis = temp;
mat = maze;
return dfs(st.first, st.second); }
vector<vector<int>> vis, mat;
pair<int, int> st, des;
int n, m;
int dirx[] = {-, , , };
int diry[] = {, -, , };
};

dfs

 class Solution {
public:
bool hasPath(vector<vector<int>>& maze, vector<int>& start, vector<int>& destination) {
st.first = start[], st.second = start[], des.first = destination[], des.second = destination[];
n = maze.size(), m = maze[].size();
vector<vector<int>> vis(n, vector<int>(m, ));
queue<pair<int, int>> que;
que.push(st);
for ( ;!que.empty(); que.pop()) {
pair<int, int> cur = que.front();
for (int i = ; i < ; ++i) {
int new_x = cur.first + dirx[i], new_y = cur.second + diry[i];
while (new_x >= && new_x < n && new_y >= && new_y < m && maze[new_x][new_y] == ) {
new_x += dirx[i], new_y += diry[i];
}
new_x -= dirx[i], new_y -= diry[i];
if (new_x == des.first && new_y == des.second) {
return true;
}
if (!vis[new_x][new_y]) {
vis[new_x][new_y] = ;
que.push(make_pair(new_x, new_y));
}
}
}
return false;
}
pair<int, int> st, des;
int n, m;
int dirx[] = {-, , , };
int diry[] = {, -, , };
};

bfs

【499】The Maze III 

题目背景和490题差不多,就是小球走迷宫。但是一开始给了一个球的位置和一个洞的位置。(不同的是本题是洞,小球经过洞就能掉下去。而上一题是停止位置,小球必须撞到障碍物才能停止。)要求返回小球能不能落进洞里,如果能,返回最短路径的方向。如果有多条最短路,那么返回方向字典序最小的那个。不好写,需要review。

题解:还是bfs。我一开始想的是用一个字符标记从这个点走的方向,但是不行。(判断不出来是不是方向字典序最短)。后来看了discuss,是用了一个string标记从开始位置到当前位置的所有的方向,这样如果有新的路径比原来的路径短,就更新string和路径长度,如果有一条新的路径和原来的路径一样长,就判断谁的字典序小就用谁。

 class Solution {
public:
string findShortestWay(vector<vector<int>>& maze, vector<int>& ball, vector<int>& hole) {
st.first = ball[], st.second = ball[], des.first = hole[], des.second = hole[];
n = maze.size(), m = maze[].size();
vector<vector<point>> cnt(n, vector<point>(m, point())); //cnt[x][y] --> (path, tot)
queue<pair<int, int>> que;
cnt[st.first][st.second].tot = ;
que.push(st);
bool findAns = false;
for ( ;!que.empty(); que.pop()) {
pair<int, int> cur = que.front();
int curx = cur.first, cury = cur.second;
for (int i = ; i < ; ++i) {
int newx = curx + dirx[i], newy = cury + diry[i], step = ;
bool onRoad = false;
while (newx >= && newx < n && newy >= && newy < m && maze[newx][newy] == ) {
//如果hole就在当前的路上,球能掉进洞里
if (newx == des.first && newy == des.second) {
findAns = true; onRoad = true;
if (cnt[newx][newy].tot == - || cnt[newx][newy].tot > step + cnt[curx][cury].tot) {
cnt[newx][newy].tot = step + cnt[curx][cury].tot;
cnt[newx][newy].path = cnt[curx][cury].path + dir2str[i];
} else if (cnt[newx][newy].tot == step + cnt[curx][cury].tot) {//如果最短路径相等,但是新的路径字典序更小,更新路径
string newPath = cnt[curx][cury].path + dir2str[i];
if (cnt[newx][newy].path > newPath) {
cnt[newx][newy].path = newPath;
}
}
break;
}
newx += dirx[i], newy += diry[i], step++;
}
//如果洞不在路上,就更新撞到墙的那个点
if (!onRoad) {
newx -= dirx[i], newy -= diry[i], step--;
if (cnt[newx][newy].tot == - || cnt[newx][newy].tot > step + cnt[curx][cury].tot) {
cnt[newx][newy].tot = step + cnt[curx][cury].tot;
cnt[newx][newy].path = cnt[curx][cury].path + dir2str[i];
que.push(make_pair(newx, newy));
} else if (cnt[newx][newy].tot == step + cnt[curx][cury].tot) { //如果最短路径相等,但是新的路径字典序更小,更新路径,然后把这个点重新放进队列里面。
string newPath = cnt[curx][cury].path + dir2str[i];
if (cnt[newx][newy].path > newPath) {
cnt[newx][newy].path = newPath;
que.push(make_pair(newx, newy));
}
}
}
}
}
string ans;
if (!findAns) {
ans = "impossible";
return ans;
}
ans = cnt[des.first][des.second].path;
return ans;
}
pair<int, int> st, des;
int n, m;
int dirx[] = {, -, , };
int diry[] = {, , , -};
string dir2str[] = {"r", "u", "d", "l"};
struct point {
point():path(""), tot(-) { }
string path; //到每个点而且满足条件的最短路径
int tot; //到每个点的最短路径长度
};
};

【505】The Maze II

题目背景和490题一样,都是小球在迷宫里面走。这题不同之处要求出小球从开始位置走到结束位置的最短距离,不可达返回-1。

题解:直接bfs了。有一点需要注意,如果有一个点到开始位置的距离更新了,那么这个点要重新放回队列里面搜索。不然最小距离更新的不准。

 class Solution {
public:
int shortestDistance(vector<vector<int>>& maze, vector<int>& start, vector<int>& destination) {
st.first = start[], st.second = start[], des.first = destination[], des.second = destination[];
n = maze.size(), m = maze[].size();
vector<vector<int>> cnt(n, vector<int>(m, -));
queue<pair<int, int>> que;
cnt[st.first][st.second] = ;
que.push(st);
bool findAns = false;
int ans = ;
for (; !que.empty(); que.pop()) {
pair<int, int> cur = que.front();
for (int i = ; i < ; ++i) {
int newx = cur.first + dirx[i], newy = cur.second + diry[i], step = ;
while (newx >= && newx < n && newy >= && newy < m && maze[newx][newy] == ) {
newx += dirx[i], newy += diry[i], step++;
}
newx -= dirx[i], newy -= diry[i], step--;
if (cnt[newx][newy] == -) {
cnt[newx][newy] = step + cnt[cur.first][cur.second];
que.push(make_pair(newx, newy));
} else if (cnt[newx][newy] > step + cnt[cur.first][cur.second]){
que.push(make_pair(newx, newy)); //如果当前点的最短距离有更新的话, 依然要push进入队列,不然最小距离不准的。
cnt[newx][newy] = min(cnt[newx][newy], step + cnt[cur.first][cur.second]) ;
}
if (newx == des.first && newy == des.second) {
findAns = true;
}
}
}
return findAns ? cnt[des.first][des.second] : -;
}
pair<int, int> st, des;
int n, m;
int dirx[] = {-, , , };
int diry[] = {, -, , };
};

【513】Find Bottom Left Tree Value

给了一棵二叉树,返回这棵树最后一层的最左边的节点的值。

题解:二叉树的层级遍历,直接bfs。

 /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int findBottomLeftValue(TreeNode* root) {
if (!root) {return -;}
queue<TreeNode*> que, que2;
vector<int> level;
que.push(root);
int ans = -;
while (!que.empty()) {
while (!que.empty()) {
TreeNode* node = que.front(); que.pop();
level.push_back(node->val);
if (node->left) { que2.push(node->left); }
if (node->right) { que2.push(node->right); }
}
swap(que, que2);
ans = level[];
level.clear();
}
return ans;
}
};

【515】Find Largest Value in Each Tree Row

给了一棵二叉树,返回每层的最大值。

题解:二叉树的层级遍历,直接bfs。

 /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> largestValues(TreeNode* root) {
vector<int> ans;
queue<TreeNode*> que, que2;
if (!root) {return ans;}
que.push(root);
while (!que.empty()) {
int maxx = INT_MIN;
while (!que.empty()) {
TreeNode* node = que.front();
que.pop();
maxx = max(node->val, maxx);
if (node->left) {que2.push(node->left);}
if (node->right) {que2.push(node->right);}
}
ans.push_back(maxx);
swap(que, que2);
}
return ans;
}
};

【529】Minesweeper

【542】01 Matrix (2019年2月23日)

Given a matrix consists of 0 and 1, find the distance of the nearest 0 for each cell.

The distance between two adjacent cells is 1.

  1. The number of elements of the given matrix will not exceed 10,000.
  2. There are at least one 0 in the given matrix.
  3. The cells are adjacent in only four directions: up, down, left and right.
Example 2:
Input:
0 0 0
0 1 0
1 1 1
Output:
0 0 0
0 1 0
1 2 1

题解:BFS

 class Solution {
public:
vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) {
if (matrix.empty() || matrix[].empty()) {return matrix;}
const int n = matrix.size(), m = matrix[].size();
vector<vector<int>> res = matrix;
queue<vector<int>> que;
for (int i = ; i < n; ++i) {
for (int j = ; j < m; ++j) {
if (matrix[i][j] == ) {
que.push({i, j});
} else {
res[i][j] = -;
}
}
}
const vector<int> dirx = {-, ,, };
const vector<int> diry = { ,-, , };
int step = ;
while (!que.empty()) {
int size = que.size();
for (int i = ; i < size; ++i, que.pop()) {
auto x = que.front()[], y = que.front()[];
for (int k = ; k < ; ++k) {
int newx = x + dirx[k], newy = y + diry[k];
if (newx < || newx >= n || newy < || newy >= m) {continue;}
if (res[newx][newy] != -) {continue;}
res[newx][newy] = step;
que.push({newx, newy});
}
}
++step;
}
return res;
}
};

【559】Maximum Depth of N-ary Tree

【675】Cut Off Trees for Golf Event

【690】Employee Importance

给了一个数据结构,[1, 15, [2]], 代表1号员工他的value是15,他的下属是2号员工。输入一个这样的数据结构的数组,和一个员工编号。返回这个员工和他所有的直接下属和间接下属的价值之和。

题解:直接bfs。

 /*
// Employee info
class Employee {
public:
// It's the unique ID of each node.
// unique id of this employee
int id;
// the importance value of this employee
int importance;
// the id of direct subordinates
vector<int> subordinates;
};
*/
class Solution {
public:
int getImportance(vector<Employee*> employees, int id) {
int ans = ;
queue<int> que;
que.push(id);
for (; !que.empty(); que.pop()) {
int user = que.front();
Employee* ptr = ;
for (int i = ; i < employees.size(); ++i) {
ptr = employees[i];
if (ptr->id == user) {
break;
}
}
if (ptr == ) {
cout << "err" << endl;
return -;
}
ans += ptr->importance;
for (int i = ; i < ptr->subordinates.size(); ++i) {
que.push(ptr->subordinates[i]);
}
}
return ans;
}
};

【743】Network Delay Time

【752】Open the Lock (2018年11月29日,算法群)

一个字符串四个字符,开始位置是 “0000”, 给了一个集合,里面限制了这个字符串不能转换到这个集合里面的元素,否则算这个游戏挂了。给了一个终点字符串 target,问从 “0000” 开始至少要经过多少步能到达 target。一步的定义是一个字符加一或者减一(0-9循环),比如,'1' -> '0' ,'0'->'1', '0'->'9', '9->0'。

题解:bfs,难点是生成下一个结点的集合。(直接暴力生成) 这题solution也是这个解法,但是300+ms,beats 10%不到。为啥呢,真的很慢了。

 //本题的重点是如何生成不在 deadends 里面的下一个结点。
class Solution {
public:
int openLock(vector<string>& deadends, string target) {
set<string> st(deadends.begin(), deadends.end());
set<string> visited;
if (st.find("") != st.end() || st.find(target) != st.end()) {return -;}
queue<string> que;
que.push(""); visited.insert("");
int step = ;
bool findAns = false;
while (!que.empty()) {
const int size = que.size();
for (int i = ; i < size; ++i) {
string cur = que.front(); que.pop();
if (cur == target) { findAns = true; break; }
vector<string> nextNodes = genNextNodes(cur, st, target);
for (auto node : nextNodes) {
if (visited.find(node) != visited.end()) {continue;}
que.push(node);
visited.insert(node);
}
}
if (findAns) { return step; }
step++;
}
return -;
}
vector<string> genNextNodes(const string& cur, const set<string>& st, const string& target) {
vector<string> ret;
string temp = cur;
for (int i = ; i < ; ++i) {
int num = temp[i] - '' + ;
for (int dis = -; dis <= ; dis +=) {
int newNum = (num + dis) % ;
string str = temp.substr(, i) + to_string(newNum) + temp.substr(i+);
if (st.find(str) != st.end()) {continue;}
ret.push_back(str);
}
}
return ret;
}
};

【773】Sliding Puzzle (2019年3月10日, H)

八数码问题

题解:bfs 用 encode棋盘成字符串的方式来保存状态。

 class Solution {
public:
int slidingPuzzle(vector<vector<int>>& board) {
queue<string> que;
string state = toString(board), target = "";
if (state == target) {return ;}
que.push(state);
unordered_set<string> st;
st.insert(state);
const int n = board.size(), m = board[].size();
int step = ;
while (!que.empty()) {
int size = que.size();
while (size--) {
string cur = que.front(); que.pop();
toBoard(cur, board);
int pos = cur.find('');
int x = pos / m, y = pos % m;
for (int k = ; k < ; ++k) {
int newx = x + dirx[k], newy = y + diry[k];
if (newx < || newx >= n || newy < || newy >= m) {continue;}
vector<vector<int>> newBoard(board);
swap(newBoard[x][y], newBoard[newx][newy]);
string newState = toString(newBoard);
if (newState == target) {return step + ;}
if (st.find(newState) != st.end()) {continue;}
st.insert(newState);
que.push(newState);
}
}
step++;
}
return -;
}
const int dirx[] = {-, , , };
const int diry[] = {, -, , };
string toString(vector<vector<int>>& board) {
string res;
for (int i = ; i < board.size(); ++i) {
for (int j = ; j < board[i].size(); ++j) {
res += board[i][j] + '';
}
}
return res;
}
void toBoard(string& s, vector<vector<int>>& board) {
int m = board[].size();
for (int i = ; i < s.size(); ++i) {
board[i/m][i%m] = s[i] - '';
}
}
};

【785】Is Graph Bipartite?

【787】Cheapest Flights Within K Stops

【815】Bus Routes

【847】Shortest Path Visiting All Nodes (算法群 2018年10月24日) 这题似懂非懂,最后写了一个BFS+状态压缩的写法。但是似乎可以dp+状态压缩。

【854】K-Similar Strings

【863】All Nodes Distance K in Binary Tree

【864】Shortest Path to Get All Keys