题目:110.字符串接龙
题目链接:
110. 字符串接龙 (kamacoder.com)
代码:
cpp
#include<bits/stdc++.h>
#include<unordered_map>
#include<unordered_set>
using namespace std;
int main() {
int n;
cin >> n;
string beginStr, endStr;
cin >> beginStr >> endStr;
set<string>MySet;
for (int i = 0; i < n; i++) {
string str;
cin >> str;
MySet.insert(str);
}
unordered_map<string, int>MyMap;
MyMap.insert(pair<string, int>(beginStr, 1));
queue<string>que;
que.push(beginStr);
while (!que.empty()) {
string word = que.front();
que.pop();
int path = MyMap[word];
for (int i = 0; i < word.size(); i++) {
string newWord = word;
for (int j = 0; j < 26; j++) {
newWord[i] = 'a' + j;
if (newWord == endStr) {
cout << path + 1 << endl;
return 0;
}
else {
if (MySet.count(newWord) && !MyMap.count(newWord)) {
MyMap.insert(pair<string, int>(newWord, path + 1));
que.push(newWord);
}
}
}
}
}
cout << 0 << endl;
return 0;
}
题目:105.有向图的完全可达性
题目链接:
105. 有向图的完全可达性 (kamacoder.com)
代码:
dfs:
cpp
#include<bits/stdc++.h>
#include<unordered_map>
#include<unordered_set>
using namespace std;
void dfs(vector<list<int>>& vec, vector<bool>& visited, int key) {
if (visited[key]) return;
visited[key] = true;
for (auto t : vec[key]) {
dfs(vec, visited, t);
}
}
int main() {
int n, k;
cin >> n >> k;
vector<list<int>>vec(n + 1);
for (int i = 0; i < k; i++) {
int s, t;
cin >> s >> t;
vec[s].push_back(t);
}
vector<bool>visited(n + 1, false);
dfs(vec, visited, 1);
for (int i = 1; i <= n; i++) {
if (visited[i] == false) {
cout << -1 << endl;
return 0;
}
}
cout << 1 << endl;
return 0;
}
bfs:
cpp
#include<bits/stdc++.h>
#include<unordered_map>
#include<unordered_set>
using namespace std;
void bfs(vector<list<int>>& vec, vector<bool>& visited, int key) {
queue<int>que;
que.push(key);
visited[key] = true;
while (!que.empty()) {
int cur = que.front();
que.pop();
visited[cur] = true;
for (auto t : vec[cur]) {
if (visited[t]) continue;
que.push(t);
}
}
}
int main() {
int n, k;
cin >> n >> k;
vector<list<int>>vec(n + 1);
for (int i = 0; i < k; i++) {
int s, t;
cin >> s >> t;
vec[s].push_back(t);
}
vector<bool>visited(n + 1, false);
bfs(vec, visited, 1);
for (int i = 1; i <= n; i++) {
if (visited[i] == false) {
cout << -1 << endl;
return 0;
}
}
cout << 1 << endl;
return 0;
}
题目:106.岛屿的周长
题目链接:
代码:
cpp
#include<bits/stdc++.h>
#include<unordered_map>
#include<unordered_set>
using namespace std;
int dir[4][2] = { 0,1,1,0,-1,0,0,-1 };
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 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 + dir[k][0];
int y = j + dir[k][1];
if (x < 0 || y < 0 || y >= grid[0].size() || x >= grid.size() || grid[x][y] == 0) {
result++;
}
}
}
}
}
cout << result << endl;
}