自己写的BFS代码
#include<bits/stdc++.h>
using namespace std;
int r, c;
char a[21][21];
int startx, starty;
bool vis[21][21];
int dx[4] = { 1,-1,0,0 };
int dy[4] = { 0,0,1,-1 };
int ans = 1;
void bfs(int x, int y) {
queue<pair<int, int> > q;
q.push(make_pair(x,y));
vis[x][y] = true;
while (!q.empty()) {
pair<int, int> now;
now = q.front();
q.pop();
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
int xx = now.first + dx[i];
int yy = now.second + dy[i];
if (xx >= 0 && xx < c && yy >= 0 && yy < r && !vis[xx][yy] && a[xx][yy] == '.') {
q.push(make_pair(xx, yy));
vis[xx][yy] = true;
ans++;
}
}
}
}
}
int num1, num2;
int main()
{
cin >> r >> c;
while(1){
memset(vis, false, sizeof(vis));
memset(a,0,sizeof(a));
ans=1;
for (int i = 0; i < c; i++) {
cin >> a[i];
}
for (int i = 0; i < c; i++) {
for (int j = 0; j < r; j++) {
if (a[i][j] == '@') {
startx = i;
starty = j;
break;
}
}
}
bfs(startx, starty);
cout << ans << endl;
cin >> r >> c;
if(r==0&&c==0)
break;
}
return 0;
}
y总 dfs的实现
#include<bits/stdc++.h>
using namespace std;
const int N = 25;
int n, m;
char g[N][N];
bool st[N][N];
int dx[4] = { -1,0,1,0 };
int dy[4] = { 0,1,0,-1 };
int dfs(int x, int y) {
int cnt = 1;
st[x][y] = true;
for (int i = 0; i < 4; i++) {
int a = x + dx[i];
int b = y + dy[i];
if (a < 0 || a >= n || b < 0 || b >= m)continue;
if (g[a][b] != '.')continue;
if (st[a][b])continue;
cnt += dfs(a, b);
}
return cnt;
}
int main()
{
while (cin >> m >> n, n || m) {
for (int i = 0; i < n; i++)
cin >> g[i];
int x, y;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (g[i][j] == '@') {
x = i;
y = j;
}
}
}
memset(st, 0, sizeof(st));
cout << dfs(x, y) << endl;
}
return 0;
}
为什么主函数中while中cin>>m>n移出来就超时了?