DFS入门刷题
目录
P1683 入门
P1596 [USACO10OCT] Lake Counting S
1114. 棋盘问题
P1025 [NOIP 2001 提高组] 数的划分
P1683 入门
#include <iostream>
using namespace std;
char a[30][30];
bool vis[30][30];
int res = 1;
int n, m;
int dx[] = {-1, 1, 0, 0};
int dy[] = {0, 0, 1, -1};
void dfs(int x, int y)
{for (int i = 0; i < 4; i++){int nx = x + dx[i];int ny = y + dy[i];if (nx >= 1 && ny >= 1 && nx <= n && ny <= m && a[nx][ny] != '#' && !vis[nx][ny]){vis[nx][ny] = true;res++;dfs(nx, ny);}}
}
int main()
{cin >> m >> n;int x, y;for (int i = 1; i <= n; i++){for (int j = 1; j <= m; j++){cin >> a[i][j];if (a[i][j] == '@'){x = i;y = j;vis[i][j] = true;}}}dfs(x, y);cout << res;return 0;
}
P1596 [USACO10OCT] Lake Counting S
#include <iostream>
using namespace std;
char a[105][105];
int n, m;
int res;
bool vis[105][105];
int dx[] = {1, -1, 0, 0, 1, -1, 1, -1};
int dy[] = {0, 0, -1, 1, -1, 1, 1, -1};
void dfs(int x, int y)
{for (int i = 0; i < 8; i++){int nx = x + dx[i];int ny = y + dy[i];if (nx >= 1 && ny >= 1 && nx <= n && ny <= m && a[nx][ny] == 'W' && !vis[nx][ny]){vis[nx][ny] = true;dfs(nx, ny);}}
}
int main()
{cin >> n >> m;for (int i = 1; i <= n; i++){for (int j = 1; j <= m; j++){cin >> a[i][j];}}for (int i = 1; i <= n; i++){for (int j = 1; j <= m; j++){if (a[i][j] == 'W' && !vis[i][j]){res++;dfs(i, j);}}}cout << res;return 0;
}
1114. 棋盘问题
#include <iostream>
using namespace std;
int n, k;
bool vis[10];
char a[10][10];
int res;
void dfs(int x, int count)
{if (k == count){res++;return;}if (x > n){return;}for (int i = 1; i <= n; i++){if (!vis[i] && a[x][i] == '#'){vis[i] = true;dfs(x + 1, count + 1);vis[i] = false;}}dfs(x + 1, count); // 强行访问
}
int main()
{while (cin >> n >> k, n > 0 && k > 0){for (int i = 1; i <= n; i++){for (int j = 1; j <= n; j++){cin >> a[i][j];}}res = 0;dfs(1, 0);cout << res << "\n";}return 0;
}
P1025 [NOIP 2001 提高组] 数的划分
#include <iostream>
using namespace std;
int n, k;
int res;
int a[10];
void dfs(int x, int sum, int start)
{if (sum > n){return;}if (x > k){if (sum == n){res++;}return;}for (int i = start; sum + (k - x + 1) * i <= n; i++){a[x] = i;dfs(x + 1, sum + i, i);a[x] = 0;}
}
int main()
{cin >> n >> k;dfs(1, 0, 1);cout << res;return 0;
}