代码随想录第五十九天打卡

110.  字符串接龙

经过上面的练习,大家可能会感觉 广搜不过如此,都刷出自信了,本题让大家初步感受一下,广搜难不在广搜本身,而是如何应用广搜。

代码随想录

#include <iostream>
#include <set>
#include <vector>
#include <map>
#include <queue>
#include <string>
using namespace std;
void solve() {
	int n;
	cin >> n;
	string beginStr, endStr, str;
	cin >> beginStr >> endStr;
	set<string>s;
	map<string, int>mp;
	for (int i = 0; i < n; i++) {
		cin >> str;
		s.insert(str);
	}
	mp.insert(pair<string, int>(beginStr, 1));
	queue <string>que;
	que.push(beginStr);
	while (!que.empty()) {
		string str=que.front();
		que.pop();
		int path = mp[str];
		for (int i = 0; i < str.size(); i++) {
			string newstr = str;
			for (int j = 0; j < 26; j++) {
				newstr[i] = j + 'a';
				if (newstr == endStr) {
					cout << path + 1 << endl;;
					return;
				}
				if (s.find(newstr) != s.end() && mp.find(newstr) == mp.end()) {
					mp.insert(pair<string, int>(newstr, path + 1));
					que.push(newstr);
				}
			}
		}
	}
	cout << 0 << endl;
}
int main() {
	solve();
	return 0;
}

总结

败在了不会找相差一个字母的字符串。

105.  有向图的完全可达性

深搜有细节,同样是深搜两种写法的区别,以及什么时候需要回溯操作呢?

代码随想录

#include <iostream>
#include <vector>
using namespace std;
int n, m;
int path = 1;//记录经过了几个节点
int flag = 0;
void dfs(vector<vector<int>>&mp,vector<bool>&visited,int startindex) {
    if (path >= n) {
        flag += 1;
        return;
    }
    for (int i = 0; i < mp[startindex].size(); i++) {
        if (visited[mp[startindex][i]] == false) {
            visited[mp[startindex][i]] = true;
            path++;
            dfs(mp,visited,mp[startindex][i]);
        }
    }
}
int solve() {
    cin >> n >> m;
    vector<bool>visited(n + 1, false);//记录访问过的节点
    visited[1] = true;
    if (n > m)return -1;
    vector<vector<int>>mp(n+1, vector<int>());
    for (int i = 0; i < m; i++) {
        int a, b;
        cin >> a >> b;
        mp[a].push_back(b);
    }
    dfs(mp,visited,1);
    if (flag)return 1;
    else return -1;
}
int main() {
    cout << solve() << endl;
    return 0;
}

106.  岛屿的周长

简单题,避免大家惯性思维,建议大家先独立做题。

代码随想录

#include <iostream>
#include <vector>
using namespace std;
int n, m;
void solve() {
	cin >> n >> m;
	int dx[] = { -1,1,0,0 };
	int dy[] = { 0,0,-1,1 };
	vector<vector<int>>mp(n, vector<int>(m, 0));
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < m; j++) {
			cin >> mp[i][j];
		}
	}
	int c = 0;
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < m; j++) {
			if (mp[i][j] == 1) {
				for (int s = 0; s < 4; s++) {
					int xx = i + dx[s], yy = j + dy[s];
					if (xx>=0 && xx<=n - 1 && yy>=0 && yy<=m - 1 && mp[xx][yy] == 1)continue;
					c++;
				}
			}
		}
	}
	cout << c << endl;
}
int main() {
	solve();
	return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值