POJ 1979 搜索 水题
2017-08-21 00:00
99 查看
题意:给你一个row*col的矩阵,上面的'#'代表你不能走的地方,'.'表示你能走的地方,'@'表示你的起点,问你最多能走多少格。
dfs
bfs
dfs
#include <iostream> #include <cstdio> #include <cmath> #include <cstring> #include <algorithm> #include <queue> #define LL long long int const MAX = 1e6 + 1; int const INF = 1 << 30; double const EPS = 0.00000001; using namespace std; int mp[20][20], n, m, ans = 0, dir[4][2] = {1, 0, -1, 0, 0, 1, 0, -1}; char s[21]; void dfs(int x, int y){ mp[x][y] = 0; for (int k = 0; k < 4; k++){ int nx = x + dir[k][0], ny = y + dir[k][1]; if (nx >= 0 && ny >= 0 && nx < n && ny < m && mp[nx][ny]){ ans++; dfs(nx, ny); } } } int main(){ freopen("in.txt", "r", stdin); freopen("out.txt", "w", stdout); int x, y; while (scanf("%d%d", &m, &n), n + m){ for (int i = 0; i < n; i++){ scanf("%s", s); for (int j = 0; j < m; j++){ mp[i][j] = (s[j] == '#' ? 0 : 1); if (s[j] == '@') x = i, y = j; } } ans = 1; dfs(x, y); printf("%d\n", ans); } return 0; }
bfs
#include <iostream> #include <cstdio> #include <cmath> #include <cstring> #include <algorithm> #include <queue> #define LL long long int const MAX = 1e6 + 1; int const INF = 1 << 30; double const EPS = 0.00000001; using namespace std; int mp[20][20], n, m, ans = 0, dir[4][2] = {1, 0, -1, 0, 0, 1, 0, -1}; char s[21]; struct Node { int x, y; }; int bfs(Node st){ int cnt = 1; queue<Node> q; q.push(st); Node t; mp[st.x][st.y] = 0; while (!q.empty()){ Node nd = q.front(); q.pop(); for (int k = 0; k < 4; k++){ t.x = nd.x + dir[k][0], t.y = nd.y + dir[k][1]; if (t.x >= 0 && t.y >= 0 && t.x < n && t.y < m && mp[t.x][t.y]){ mp[t.x][t.y] = 0; q.push(t); cnt++; } } } return cnt; } int main(){ freopen("in.txt", "r", stdin); freopen("out.txt", "w", stdout); Node st; while (scanf("%d%d", &m, &n), n + m){ for (int i = 0; i < n; i++){ scanf("%s", s); for (int j = 0; j < m; j++){ mp[i][j] = (s[j] == '#' ? 0 : 1); if (s[j] == '@') st.x = i, st.y = j; } } printf("%d\n", bfs(st)); } return 0; }
相关文章推荐
- POJ-1979(搜索水题)
- POJ 1979 —— 搜索
- poj 1753 Flip Game(搜索:DFS+水题)
- poj1543 Perfect Cubes (搜索,水题)
- 解题报告_POJ1979-red and black_深搜水题
- POJ 2028 When Can We Meet?(我的水题之路——边输入,边搜索)
- poj 1979 dfs水题
- POJ 1979 Red and Black (DFS水题)
- ZOJ 2165 POJ 1979 Red and Black DFS水题
- poj 1979 搜索
- poj 1979 Red and Black (简单裸搜索)
- POJ 1979 - Red and Black 深度优先搜索
- POJ 1979 Red and Black DFS水题
- poj 1979 Red and Black(dfs水题)
- poj 1979 简单的搜索
- POJ 1979 深度优先搜索
- poj1979 dfs水题
- poj 2138 Travel Games 搜索+自动机水题
- 深度优先搜索【POJ 1979】
- POJ 1979 基础搜索 DFS\BFS 一