2.1.4 部分和dfs
#include <iostream>
#include <cstdio>
using namespace std;
int n,
sum;
int numberset[20] = {0};
bool dfs(int x, int sumnow)
{
if(x == n)
{
return sumnow == sum;
}
else
{
if(dfs(x + 1, sumnow + numberset[x]))
return true;
if(dfs(x + 1, sumnow))
return true;
return false;
}
}
int main()
{
freopen("in.txt","r",stdin);
cin >> n;
for(int i = 0;i < n;i++)
{
cin >> numberset[i];
}
cin >> sum;
if(dfs(0, 0))
cout << "YES" << endl;
else
cout << "NO" << endl;
return 0;
}
2.1.4 Lake Counting dfs
#include <iostream>
#include <cstdio>
using namespace std;
char court[101][101];
int step[8][2] = {{-1, -1}, {-1, 1}, {1, 1}, {1, -1}, {-1, 0}, {1, 0}, {0, 1}, {0, -1}};
int m, n;
void dfs(int x, int y)
{
if(x < 0 || y < 0 || x > m || y > n)
return;
court[x][y] = '.';
for(int i = 0;i < 8; i++)
{
int tempx = x, tempy = y;
tempx += step[i][0];
tempy += step[i][1];
if(court[tempx][tempy] == 'W')
dfs(tempx, tempy);
}
}
int main()
{
freopen("in.txt","r",stdin);
cin >> m >> n;
for(int i = 0;i < m; i++)
for(int j = 0;j < n; j++)
cin >> court[i][j];
int timecount = 0;
for(int i = 0;i < m; i++)
{
for(int j = 0;j < n; j++)
{
if(court[i][j] == 'W')
{
dfs(i, j);
timecount++;
}
}
}
cout << timecount;
return 0;
}
2.1.5 走迷宫bfs
#include <iostream>
#include <cstdio>
#include <queue>
using namespace std;
typedef pair<int, int> P;
int n, m,
sx, sy, gx, gy;
const int INF = 10000000;
int dis[101][101],
movestep[4][2] = {{1,0}, {-1,0} , {0,1}, {0,-1}};
char ditu[101][101];
void bfs()
{
queue<P> que;
for(int i = 0;i < n;i++)
{
for(int j = 0;j < m;j++)
{
dis[i][j] = INF;
}
}
que.push(P(sx,sy));
dis[sx][sy] = 0;
while(que.size())
{
P p = que.front();
que.pop();
if(p.first == gx && p.second == gy)
break;
int tempx, tempy;
for(int i = 0;i < 4;i++)
{
tempx = p.first + movestep[i][0];
tempy = p.second + movestep[i][1];
if(tempx >= 0 && tempy >= 0 && tempx < n && tempy < m && ditu[tempx][tempy] != '#' && dis[tempx][tempy] == INF)
{
que.push(P(tempx, tempy));
dis[tempx][tempy] = dis[p.first][p.second] + 1;
}
}
}
}
int main()
{
freopen("in.txt","r",stdin);
cin >> n >> m;
for(int i = 0;i < n; i++)
{
for(int j = 0;j < m; j++)
{
cin >> ditu[i][j];
if(ditu[i][j] == 'S')
{
sx = i;
sy = j;
}
if(ditu[i][j] == 'G')
{
gx = i;
gy = j;
}
}
}
bfs();
cout << dis[gx][gy];
return 0;
}