全球变暖
https://www.lanqiao.cn/problems/178/learning/?page=1&first_category_id=1&sort=students_count&problem_id=178
- 解释:
要注意不管是dfs还是bf一次进入到的都是一座完整的岛屿,如果有n座岛屿,会进入n次dfs
- 代码:
#include <iostream>
using namespace std;
int N;
char nums[10001][10001];
bool gr[10001][10001];
int dir[4][2] = {{-1, 0}, {0, -1}, {0, 1}, {1, 0}};
bool flag;//该座岛屿是否被淹没
int ans;
bool in(int x, int y) {
return 0 <= x && x < N && 0 <= y && y < N;
}
//判断是不是可以保留
bool ishas(int x, int y) {
bool f = true;
f = f && nums[x][y] == '#';
for(int i = 0; i < 4; i++) {
int tx = x + dir[i][0];
int ty = y + dir[i][1];
if(in(tx, ty)){
f = f && nums[tx][ty] == '#';
}
}
return f;
}
//一次只进入了一座岛屿
void dfs(int x, int y) {
if(ishas(x, y)) {
flag = false;
}
for(int i = 0; i < 4; i++) {
int tx = x + dir[i][0];
int ty = y + dir[i][1];
if(in(tx, ty) && !gr[tx][ty] && nums[tx][ty] == '#') {
gr[tx][ty] = true;
dfs(tx, ty);
}
}
}
int main()
{
// 请在此输入您的代码
cin >> N;
for(int i = 0; i < N; i++) {
cin >> nums[i];
}
for(int i = 0; i < N; i++) {
for(int j = 0; j < N; j++) {
if(nums[i][j] == '#' && !gr[i][j]){
gr[i][j] = true;
flag = true;
dfs(i, j);
if(flag == true) {
ans++;
}
}
}
}
cout << ans;
return 0;
}
剪邮票
https://www.lanqiao.cn/problems/1505/learning/?page=1&first_category_id=1&sort=students_count&problem_id=1505
- 解释:
这道题目麻烦的地方是要判断他们是不是连接在一起的,判断依据是path内部的五个数全部进队了,而且要连接在一起(通过in函数判断)
- 代码
#include <iostream>
#include<algorithm>
#include<vector>
#include<string.h>
#include<queue>
using namespace std;
int nums[12];
int grid[3][4];
bool used[12];
int dir[4][2] = {{-1, 0}, {0, -1}, {0, 1}, {1, 0}};
vector<int> path;
int ans;
bool in(int x, int y) {
return 0 <= x && x < 3 && 0 <= y && y < 4;
}
int iscon() {
int p = 0;
queue<pair<int, int>> q;
q.push({path[0]/4, path[0]%4});
used[path[0]] = true;
while(!q.empty()) {
pair<int, int> top = q.front();
q.pop();
//cout << 4*top.first + top.second << "出队" << endl;
p++;
for(int i = 0; i < 4; i++) {
int tx = top.first + dir[i][0];
int ty = top.second + dir[i][1];
if(in(tx, ty)) {
for(int j = 1; j < 5; j++) {
if(4*tx + ty == path[j] && !used[path[j]]) {
used[path[j]] = true;
q.push({tx, ty});
}
}
}
}
}
return p;
}
void dfs(int indx) {
if(path.size() == 5) {
memset(used, 0, sizeof(used));
if(iscon() == 5) {
ans++;
}
return;
}
for(int i = indx; i < 12; i++) {
path.push_back(nums[i]);
dfs(i + 1);
path.pop_back();
}
}
int main()
{
// 请在此输入您的代码
for(int i = 0; i < 12; i++) {
nums[i] = i;
}
dfs(0);
// for(int i = 0; i < result.size(); i++) {
// for(int j = 0; j < result[i].size(); j++) {
// cout << result[i][j] << " ";
// }
// cout << endl;
// }
cout << ans;
return 0;
}