代码随想录Day53|110. 字符串接龙、105.有向图的完全联通、106. 岛屿的周长
目录
- 110. 字符串接龙
- 解题思路
- 解法
- 105.有向图的完全联通
- 解题思路
- 解法
- 106. 岛屿的周长
- 解题思路
- 解法
- 今日总结
110. 字符串接龙
题目链接:KamaCoder
文章讲解:代码随想录
视频讲解:bilibili
解题思路
本题细节很多,因为需要求的是最短路径,用广搜的方式最为直接。使用队列记录扩散遍历对象,使用集合记录遍历过的对象,防止重复遍历陷入死循环,队列中还记录着到达该字符串的路径长度。
解法
#include <iostream>
#include <vector>
#include <unordered_set>
#include <queue>
#include <algorithm>
using namespace std;int main(){int n;cin >> n;string beginStr, endStr;cin >> beginStr >> endStr;string str;unordered_set<string> strset;for(int i=0; i<n; i++){cin >> str;strset.insert(str);}unordered_set<string> visited;queue<pair<int, string>> que;que.push(make_pair(1, beginStr));visited.insert(beginStr);while(!que.empty()){string word = que.front().second;int path = que.front().first;que.pop();int length = word.size();for(int i=0; i<length; i++){string word_amend = word;for(int j=0; j<26; j++){word_amend[i] = 'a' + j;if(word_amend[i] == word[i])continue;if(word_amend == endStr){cout << path+1 << endl;return 0;}if(strset.count(word_amend) && !visited.count(word_amend)){visited.insert(word_amend);que.push(make_pair(path+1, word_amend));}}}}cout << 0 << endl;return 0;
}
- 时间复杂度: O ( n ) O(n) O(n)
- 空间复杂度: O ( n ) O(n) O(n)
105.有向图的完全联通
题目链接:KamaCoder
文章讲解:代码随想录
视频讲解:bilibili
解题思路
相比前面的题目来说较为基础,深搜广搜均可,这里使用深搜进行寻找,访问一个节点就遍历一次,如果全部结束之后还有节点未被访问,则说明图不连通。
解法
#include <iostream>
#include <vector>
using namespace std;void dfs(int node, int n, const vector<vector<int>>& link, vector<bool>& visited){visited[node] = true;for(int j=1; j<=n; j++){if(link[node][j] && !visited[j]){dfs(j, n, link, visited);}}return ;
}int main(){int n, k;cin >> n >> k;if(k < n){cout << -1 << endl;return 0;}vector<vector<int>> link(n+1, vector<int>(n+1, 0));vector<bool> visited(n+1, false);for(int i=0; i<k; i++){int x, y;cin >> x >> y;link[x][y] = 1;}dfs(1, n, link, visited);for(int i=1; i<=n; i++){if(!visited[i]){cout << -1 << endl;return 0; }}cout << 1 << endl;return 0; }
- 时间复杂度: O ( n 2 ) O(n^2) O(n2)
- 空间复杂度: O ( n 2 ) O(n^2) O(n2)
106. 岛屿的周长
题目链接:KamaCoder
文章讲解:代码随想录
视频讲解:bilibili
解题思路
本题要计算的是岛屿的周长,也即最外围矩形的外围长度之和。对于某一个陆地单元来说,如果它与一个陆地相邻,那么对于周长的贡献就会减少1,最多可以贡献4的周长,即孤岛。这样,只要计算每个陆地的相邻陆地数量,就可以算出每个陆地单元对于周长的贡献。
解法
#include <iostream>
#include <vector>
using namespace std;int dir[4][2] = {{0,-1}, {0,1}, {1,0}, {-1,0}};int main(){int n, m;cin >> n >> m;vector<vector<int>> land(n+2, vector<int>(m+2, 0));for(int i=1; i<=n; i++)for(int j=1; j<=m; j++)cin >> land[i][j];int s=0;for(int i=1; i<=n; i++){for(int j=1; j<=m; j++){if(land[i][j]){int count = 0;for(int k=0; k<4; k++){int nextx = i + dir[k][0];int nexty = j + dir[k][1];if(land[nextx][nexty])count++;}s += 4-count;}}}if(s>0)cout << s;elsecout << 0;return 0;
}
- 时间复杂度: O ( n m ) O(nm) O(nm)
- 空间复杂度: O ( n m ) O(nm) O(nm)
今日总结
补卡中()