110.字符串接龙
cpp
#include<iostream>
using namespace std;
#include<vector>
#include<unordered_map>
#include<unordered_set>
#include<queue>
#include<string>
int main(){
int n;
cin>>n;
string beginStr,endStr;
cin>>beginStr>>endStr;
unordered_map<string, int> strmap;//用来记录起点到该字符串最短路径,并用来判断某字符串是否被访问过,如果map中找不到对应的str就说明没访问过
unordered_set<string> strset;//用来存放若干个需要出现过的字符串
//把六个字符串加入集合
for(int i=0;i<n;i++){
string appearStr;
cin>>appearStr;
strset.insert(appearStr);
}
queue<string> que;//用来把"待寻找相邻节点的字符串"入队
//把起点加入队列
que.push(beginStr);
//同时要更新strmap,标记起点作为key的话,最短路径为1
strmap[beginStr] = 1;
//开始循环入队直到队空(需要注意,访问过的节点不能重复访问,否则会死循环,因为访问节点之前一定要判断节点是否访问过),执行广搜
while(!que.empty()){
string curStr = que.front();que.pop();
for(int i=0;i<curStr.size();i++){
string newStr = curStr;//以原字符串为基础定义新字符串,新字符串是原字符串用26个字母中某个字母替代某个字母位得到的
for(int j=0;j<26;j++){
newStr[i] = j+'a';//把第i个字母替换为了a后面第j个字母
if(newStr == endStr){
cout<<strmap[curStr]+1<<endl;
return 0;
}
if(strset.find(newStr)!=strset.end() && strmap.find(newStr) == strmap.end()){
que.push(newStr);
strmap[newStr] = strmap[curStr]+1;
}
}
}
}
cout<<0<<endl;
}
105.有向图的完全可达性
cpp
#include<iostream>
#include<list>
#include<vector>
using namespace std;
void dfs(vector<list<int>>& graph, int node, vector<bool>& visited){
if(visited[node] == true) return;
visited[node] =true;
list<int> nodes = graph[node];
for(int newnode:nodes){
dfs(graph, newnode, visited);
}
}
int main(){
int n,k,s,t;
cin>>n>>k;
vector<list<int>> graph(n+1);
while(k--){
cin>>s>>t;
graph[s].push_back(t);
}
vector<bool> visited(n+1,false);
dfs(graph, 1, visited);
for(int i=1;i<=n;i++){
if(visited[i] == false){
cout<<-1<<endl;
return 0;
}
}
cout<<1<<endl;
}
106.岛屿的周长
cpp
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n, m;
cin >> n >> m;
vector<vector<int>> grid(n, vector<int>(m, 0));
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> grid[i][j];
}
}
int direction[4][2] = {0, 1, 1, 0, -1, 0, 0, -1};
int result = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (grid[i][j] == 1) {
for (int k = 0; k < 4; k++) { // 上下左右四个方向
int x = i + direction[k][0];
int y = j + direction[k][1]; // 计算周边坐标x,y
if (x < 0 // x在边界上
|| x >= grid.size() // x在边界上
|| y < 0 // y在边界上
|| y >= grid[0].size() // y在边界上
|| grid[x][y] == 0) { // x,y位置是水域
result++;
}
}
}
}
}
cout << result << endl;
}