卡码网110 字符串接龙
这题一开始用的邻接表+dfs,不幸超时
#include <iostream>
#include <list>
#include <string>
#include <vector>
using namespace std;
int minLen = 501;
bool count(string a, string b) {
int num = 0;
for (int i = 0; i < a.length() && i < b. length(); i++) {
if (a[i] != b[i]) {
num++;
if (num > 1) return false;
}
}
return true;
}
int dfs(string* s, vector<list<int>>& l, int* visited, int len, int index, int n) {
if (index == n + 1) {
if (minLen > len) minLen = len;
return len;
}
int result = 501;
for (auto it = l[index].begin(); it != l[index].end(); it++) {
if (!visited[*it]) {
visited[*it] = 1;
result = dfs(s, l, visited, len+1, *it, n);
visited[*it] = 0;
}
}
return min(minLen, result);
}
int main() {
int n;
cin >> n;
string s[n+2];
cin >> s[0] >> s[n+1];
for (int i = 1; i <= n; i++) {
cin >> s[i];
}
vector<list<int>> l(n+1);
for (int i = 0; i <= n; i++) {
for (int j = 1; j <= n+1; j++) {
if (j != i) {
if (count(s[i], s[j])) l[i].push_back(j);
}
}
}
int visited[n+2];
for (int i = 0; i < n+2; i++) visited[i] = 0;
visited[0] = 1;
minLen = dfs(s, l, visited, 1, 0, n);
if (minLen == 501) cout << 0 << endl;
else cout << minLen << endl;
}
题解中用的广搜,可以去看下,说是最短路径用深搜比较麻烦,要确定哪条最短,我确定出来了,但还是超时了。广搜只要搜到就一定是最短路径了,先放这。
卡码网105 有向图的完全可达性
这题就比较轻松了,深搜也不需要完全回溯,只需要遍历记录即可
代码如下:
#include <iostream>
#include <list>
#include <vector>
#include <queue>
using namespace std;
void bfs(vector<list<int>>& l, vector<int>& visited, int index) {
queue<int> myque;
myque.push(index);
while (!myque.empty()) {
for (int i : l[index]) {
if (!visited[i]) {
visited[i] = 1;
myque.push(i);
}
}
myque.pop();
}
}
int main() {
int n, k;
cin >> n >> k;
int s, t;
vector<list<int>> l(n);
for (int i = 0; i < k; i++) {
cin >> s >> t;
l[s-1].push_back(t-1);
}
vector<int> visited(n, 0);
visited[0] = 1;
bfs(l, visited, 0);
for (int i = 0; i < n; i++) {
if (!visited[i]) {
cout << -1 << endl;
return 0;
}
}
cout << 1 << endl;
return 0;
}
卡码网106 岛屿的周长
这题很简单,没用到dfs和bfs,简单填充边界后判断周围是否触碰边界后计数即可。
代码如下:
#include <iostream>
using namespace std;
int main() {
int n, m;
cin >> n >> m;
int g[n][m];
int sum = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> g[n][m];
}
}
for (int i = 1; i < n - 1; i++) {
for (int j = 1; j < m - 1; j++) {
if (g[i][j] == 1) {
if (g[i-1][j] == 0) sum++;
if (g[i][j-1] == 0) sum++;
if (g[i+1][j] == 0) sum++;
if (g[i][j+1] == 0) sum++;
}
}
}
cout << sum << endl;
}
标签:卡码,index,int,十七天,++,vector,visited,include,可达性
From: https://blog.csdn.net/qq_63149342/article/details/139897498