Problem Link : http://lightoj.com/volume_showproblem.php?problem=1012
Solution :
#include<bits/stdc++.h>
#define pii pair<int,int>
using namespace std;
int cell[21][21];
int visited[21][21];
int fx[]= {1,-1,0,0};
int fy[]={0,0,1,-1};
int r,c;
int bfs(pii s)
{
memset(visited,0,sizeof(visited));
visited[s.first][s.second]=1;
queue<pii>q;
pii u,a;
int x,y,cnt=0;
q.push(s);
while(!q.empty())
{
u=q.front();
q.pop();
for(int i=0;i<4;i++)
{
x=fx[i]+u.first;
y=fy[i]+u.second;
if(x>=0 and x<r and y>=0 and y<c and cell[x][y]!=2 and visited[x][y]==0)
{
visited[x][y]=1;
cnt++;
a.first=x;
a.second=y;
q.push(a);
}
}
}
return cnt+1;
}
int main()
{
int t,ans;
char ch;
pii s;
scanf("%d",&t);
for(int ca=1; ca<=t; ca++)
{
scanf("%d%d",&c,&r);
getchar();
memset(cell,-1,sizeof(cell));
for(int i=0; i<r; i++)
{
for(int j=0; j<c; j++)
{
scanf("%c",&ch);
if(ch=='.') cell[i][j]=1;
else if(ch=='#') cell[i][j]=2;
else
{
cell[i][j]=3;
s.first=i;
s.second=j;
}
}
getchar();
}
ans=bfs(s);
printf("Case %d: %d\n",ca,ans);
}
}
Solution :
#include<bits/stdc++.h>
#define pii pair<int,int>
using namespace std;
int cell[21][21];
int visited[21][21];
int fx[]= {1,-1,0,0};
int fy[]={0,0,1,-1};
int r,c;
int bfs(pii s)
{
memset(visited,0,sizeof(visited));
visited[s.first][s.second]=1;
queue<pii>q;
pii u,a;
int x,y,cnt=0;
q.push(s);
while(!q.empty())
{
u=q.front();
q.pop();
for(int i=0;i<4;i++)
{
x=fx[i]+u.first;
y=fy[i]+u.second;
if(x>=0 and x<r and y>=0 and y<c and cell[x][y]!=2 and visited[x][y]==0)
{
visited[x][y]=1;
cnt++;
a.first=x;
a.second=y;
q.push(a);
}
}
}
return cnt+1;
}
int main()
{
int t,ans;
char ch;
pii s;
scanf("%d",&t);
for(int ca=1; ca<=t; ca++)
{
scanf("%d%d",&c,&r);
getchar();
memset(cell,-1,sizeof(cell));
for(int i=0; i<r; i++)
{
for(int j=0; j<c; j++)
{
scanf("%c",&ch);
if(ch=='.') cell[i][j]=1;
else if(ch=='#') cell[i][j]=2;
else
{
cell[i][j]=3;
s.first=i;
s.second=j;
}
}
getchar();
}
ans=bfs(s);
printf("Case %d: %d\n",ca,ans);
}
}
No comments:
Post a Comment