ZOJ 2165 Red and Black
1.采用dfs:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
using namespace std;
char map[25][25];
int count = 1;
int r,c;
int dx[4] = {1,-1,0,0};
int dy[4] = {0,0,1,-1};
bool judge(int x,int y)
{
if(x<0 || x>= r || y < 0 ||y>=c)
return 0;
return 1;
}
void dfs(int x,int y)
{
map[x][y] = '#';
int nx = 0;
int ny = 0;
for(int i = 0 ; i < 4; i++)
{
nx = x + dx[i];
ny = dy[i] + y;
if(!judge(nx,ny))
continue;
if(map[nx][ny] == '.')
{
count++;
dfs(nx,ny);
}
}
}
int main()
{
//freopen("test.in", "r", stdin);
while(cin>>c>>r && r&&c)
{
count = 1;
int x0,y0;
for(int i = 0; i < r; i++ )
{
for(int j = 0 ; j < c; j++)
{
cin>>map[i][j];
if(map[i][j] == '@')
{
x0 = i;
y0 = j;
}
}
}
dfs(x0,y0);
cout<<count<<endl;
}
return 0;
}
2.bfs:
#include <iostream> #include <queue> using namespace std; structnode { int r; int l;}; int m, n, sr, sl; int dir[2][4] = {{-1, 1, 0, 0}, {0, 0, -1, 1}}; int visited[20][20]; int BFS(); int main() { int i, j; char str[21]; while(cin >> m >> n) { if(m == 0 || n == 0) { break; } for(i = 0; i < n; i++) { cin >> str; for(j = 0; j < m; j++) { if(str[j] == '@') { sr = i; sl = j; visited[i][j] = 1; } else if(str[j] == '.') { visited[i][j] = 0; } else { visited[i][j] = 1; } } } int count = BFS(); cout << count << endl; } return 0; } int BFS() { int i, count; queue<node>Q; nodeN, temp; N.r = sr; N.l = sl; count = 1; Q.push(N); while(!Q.empty()) { temp = Q.front(); Q.pop(); for(i = 0; i < 4; i++) { N = temp; N.r += dir[0][i]; N.l += dir[1][i]; if(N.r < 0 || N.r >= n || N.l < 0 || N.l >= m) { continue; } else { if(!visited[N.r][N.l]) { count++; visited[N.r][N.l] = 1; Q.push(N); } } } } return count; }