算法训练营|图论第4天 110.字符串接龙 105.有向图的完全可达性 106.岛屿的周长

题目:110.字符串接龙

题目链接:

110. 字符串接龙 (kamacoder.com)
代码:

#include
#include
#include
using namespace std;
int main() {
	int n;
	cin >> n;
	string beginStr, endStr;
	cin >> beginStr >> endStr;
	setMySet;
	for (int i = 0; i < n; i++) {
		string str;
		cin >> str;
		MySet.insert(str);
	}
	unordered_mapMyMap;
	MyMap.insert(pair(beginStr, 1));
	queueque;
	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(newWord, path + 1));
						que.push(newWord);
					}
				}
			}
		}
	}
	cout << 0 << endl;
	return 0;
}

题目:105.有向图的完全可达性

题目链接:

105. 有向图的完全可达性 (kamacoder.com)

代码:

dfs:

#include
#include
#include
using namespace std;
void dfs(vector>& vec, vector& 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>vec(n + 1);
	for (int i = 0; i < k; i++) {
		int s, t;
		cin >> s >> t;
		vec[s].push_back(t);
	}
	vectorvisited(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:

#include
#include
#include
using namespace std;
void bfs(vector>& vec, vector& visited, int key) {
	queueque;
	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>vec(n + 1);
	for (int i = 0; i < k; i++) {
		int s, t;
		cin >> s >> t;
		vec[s].push_back(t);
	}
	vectorvisited(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.岛屿的周长

题目链接:

106. 岛屿的周长 (kamacoder.com)

代码:

#include
#include
#include
using namespace std;
int dir[4][2] = { 0,1,1,0,-1,0,0,-1 };
int main() {
	int n, m;
	cin >> n >> m;
	vector>grid(n, vector(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;
}

你可能感兴趣的:(算法,图论)