其实,以前是不知道有些小范围内的BFS是可以用递归来写的。
写起来也是非常的方便的,也不知道多大的范围用递归写就会超栈,
但是这种思路还是值得提倡的。一会在用BFS写一下,好久没有写过了。
贴出代码:
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <string>
using namespace std;
char G[22][22];
int H, W;
int startX, startY;
int fun(int x, int y)
{
if (x < 0 || x >= H || y < 0 || y >= W)
{
return 0;
}
if (G[x][y] == '#')
{
return 0;
}
if (G[x][y] == '.' || G[x][y] == '@')
{
G[x][y] = '#';
return 1 + fun(x - 1, y) + fun(x + 1, y) +
fun(x, y - 1) + fun(x, y + 1);
}
}
int main()
{
while (scanf("%d%d", &W, &H) != EOF)
{
if (H == 0 && W == 0)
{
break;
}
for (int i = 0; i < H; i++)
{
getchar();
for (int j = 0; j < W; j++)
{
scanf("%c", &G[i][j]);
if (G[i][j] == '@')
{
startX = i;
startY = j;
}
}
}
int ans = fun(startX, startY);
printf("%d\n", ans);
}
// system("pause");
return 0;
}
DFS的写法...居然WA了两次是因为没有加N=0,M=0的条件,我哭;
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <string>
#include <queue>
using namespace std;
int N, M;
char G[55][55];
int startX, startY;
int vis[55][55];
int d_x[4] = {1, -1, 0, 0};
int d_y[4] = {0, 0, 1, -1};
struct node
{
int x, y;
node()
{
x = 0;
y = 0;
}
};
bool judge(int x, int y)
{
if (x < 0 || x >= N || y < 0 || y >= M || G[x][y] == '#')
{
return 0;
}
return 1;
}
int BFS()
{
int sum = 1;
queue <node> Q;
node n;
n.x = startX;
n.y = startY;
vis[startX][startY] = 1;
Q.push(n);
while (!Q.empty())
{
n = Q.front();
Q.pop();
for (int i = 0; i < 4; i++)
{
int x = n.x + d_x[i];
int y = n.y + d_y[i];
if (judge(x, y) && !vis[x][y])
{
vis[x][y] = 1;
// cout << "x = " << x << " ";
// cout << "y = " << y << endl;
sum++;
node t;
t.x = x;
t.y = y;
Q.push(t);
}
}
}
return sum;
}
int main()
{
while (scanf("%d%d", &M, &N) != EOF)
{
if (N == 0 && M == 0)
{
break;
}
memset(vis, 0, sizeof(vis));
for (int i = 0; i < N; i++)
{
scanf("%s", G[i]);
for (int j = 0; j < M; j++)
{
if (G[i][j] == '@')
{
startX = i;
startY = j;
}
}
}
int ans = BFS();
printf("%d\n", ans);
}
return 0;
}