DFS
回溯算法,其实就是dfs的过程,这里给出dfs的代码框架:
1 2 3 4 5 6 7 8 9 10 11 12
| void dfs(参数) { if (终止条件) { 存放结果; return; }
for (选择:本节点所连接的其他节点) { 处理节点; dfs(图,选择的节点); 回溯,撤销处理结果 } }
|
深搜代码模板,该模板针对的是四方格的地图:
1 2 3 4 5 6 7 8 9 10 11 12
| int dir[4][2] = {0, 1, 1, 0, -1, 0, 0, -1}; void dfs(vector<vector<char>>& grid, vector<vector<bool>>& visited, int x, int y) { for (int i = 0; i < 4; i++) { int nextx = x + dir[i][0]; int nexty = y + dir[i][1]; if (nextx < 0 || nextx >= grid.size() || nexty < 0 || nexty >= grid[0].size()) continue; if (!visited[nextx][nexty]) { visited[nextx][nexty] = true; dfs(grid, visited, nextx, nexty); } } }
|
BFS
广搜代码模板,该模板针对的是四方格的地图:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| int dir[4][2] = {0, 1, 1, 0, -1, 0, 0, -1};
void bfs(vector<vector<char>>& grid, vector<vector<bool>>& visited, int x, int y) { queue<pair<int, int>> que; que.push({x, y}); visited[x][y] = true; while(!que.empty()) { pair<int ,int> cur = que.front(); que.pop(); int curx = cur.first; int cury = cur.second; for (int i = 0; i < 4; i++) { int nextx = curx + dir[i][0]; int nexty = cury + dir[i][1]; if (nextx < 0 || nextx >= grid.size() || nexty < 0 || nexty >= grid[0].size()) continue; if (!visited[nextx][nexty]) { que.push({nextx, nexty}); visited[nextx][nexty] = true; } } } }
|