1113. 红与黑
题意:
从@出发,问能走多少次“.”。每次只能走点。
思路:
简单走迷宫。
AC(抽风大佬的dfs)
# include <bits/stdc++.h>
using namespace std;
int ans=0, sx, sy;
char g[30][30];
int dx[]={
0,0,1,-1};
int dy[]={
1,-1,0,0};
void dfs(int x, int y){
ans++;
for(int i = 0; i < 4; i ++ ){
int a = x+dx[i];
int b = y + dy[i];
if(g[a][b]=='.') g[a][b] = 0,dfs(a,b);
}
}
int main(){
int n, m;
while(cin>>m>>n,n||m){
ans = 0;
memset(g,0,sizeof(g));
for(int i = 1; i<= n; i ++ ){
cin>> g[i]+1;
for(int j = 1; j <= m; j ++ ){
if(g[i][j] == '@')sx = i, sy =j;
}
}
dfs(sx,sy);
cout<<ans<<endl;
}
return 0;
}
AC(我的bfs,不用标记,直接改就好了)
# include <bits/stdc++.h>
# define mp make_pair
using namespace std;
typedef pair<int,int> pa;
int dx[]={
0,1,-1,0};
int dy[]={
1,0,0,-1};
int vis[30][30];
char g[30][30];
int main(){
int n, m, sx, sy;
while(cin>>m>>n){
if(n==0&&m==0)break;
memset(vis,0,sizeof(vis));
for(int i = 1; i <= n; i ++ ){
for(int j = 1; j <= m; j ++) {
cin>>g[i][j];
if(g[i][j]=='@'){
sx = i, sy = j;
}
}
}
queue<pa>q;
q.push(mp(sx,sy));
int ans = 0;
while(!q.empty()){
int x = q.front().first;
int y = q.front().second;q.pop();
if(vis[x][y]) continue;
vis[x][y] = 1;
ans++;
for(int i = 0; i < 4; i ++ ){
int tx = x + dx[i];
int ty = y + dy[i];
if(tx>=1 && tx<=n && ty>=1 && ty<= m && !vis[tx][ty] && g[tx][ty]=='.')q.push(mp(tx,ty));
}
}
cout<<ans<<endl;
}
return 0;
}