4 solutions
-
0
#include<iostream> #include<queue> using namespace std; #define N 25 struct point{ int x; int y; }; queue<point> q; char a[N][N];//存地图 bool v[N][N]; int dx[4]={0,1,0,-1}; int dy[4]={1,0,-1,0}; int w,h,cnt; point start; int main() { //w列 h行 格子为h*w规格棋盘 cin>>w>>h; for(int i=0;i<h;i++) for(int j=0;j<w;j++){ cin>>a[i][j]; if(a[i][j]=='@'){ start.x=i; start.y=j; } } q.push(start); v[start.x][start.y]=true; while(!q.empty()){ point header=q.front(); for(int i=0;i<4;i++){ point temper=header; temper.x+=dx[i]; temper.y+=dy[i]; if(a[temper.x][temper.y]=='.'&&!v[temper.x][temper.y])q.push(temper); v[temper.x][temper.y]=true; } q.pop(); cnt++; } cout<<cnt<<endl; return 0; }
-
0
w, h = map(int, input().split()) m = [] s = (-1, -1) for i in range(h): line = input() m.append(line) if("@" in line): s = (i, line.index("@")) ans = 1 direct = [(1, 0), (0, 1), (-1, 0), (0, -1)] vis = [[True]*w for _ in range(h)] def check(x, y): if(x<0 or y<0 or x>=h or y>=w): return False if(not vis[x][y]): return False if(m[x][y]!='.'): return False return True ans = 1 def dfs(x, y): global ans for dx, dy in direct: nx = x + dx ny = y + dy if(check(nx, ny)): vis[nx][ny] = False ans+=1 dfs(nx, ny) dfs(*s) print(ans)
bfs
from collections import deque ans = 1 def bfs(s): global ans q = deque() q.append(s) while (len(q) != 0): tx, ty = q.popleft() for dx, dy in direct: nx = tx + dx ny = ty + dy if (check(nx, ny)): vis[nx][ny] = False ans += 1 q.append((nx, ny)) bfs(s) print(ans)
-
0
#include #include #include using namespace std; int W,H,ans=1; vector<vector > A; bool vit[20][20]; void dfs(int x,int y){
if(y+1<W&&A[x][y+1]=="."&&!vit[x][y+1]) { ans++; vit[x][y+1]=1; dfs(x,y+1); } if(x+1<H&&A[x+1][y]!="#"&&!vit[x+1][y]) { ans++; vit[x+1][y]=1; dfs(x+1,y); } if(y-1>=0&&A[x][y-1]!="#"&&!vit[x][y-1]) { ans++; vit[x][y-1]=1; dfs(x,y-1); } if(x-1>=0&&A[x-1][y]=="."&&!vit[x-1][y]) { ans++; vit[x-1][y]=1; dfs(x-1,y); }
// return; } int main(){ char ch; int x,y; cin>>W>>H; vector<vector > B(H,vector (W)); for(int i=0;i<H;i++) { for(int j=0;j<W;j++) { cin>>ch; B[i][j]=ch; if(B[i][j]=="@") { x=i;y=j; vit[i][j]=1; } } } A=B; dfs(x,y); cout<<ans<<endl; return 0; }
-
0
#include<bits/stdc++.h> using namespace std; int n,m,ans=0; char f[25][25]; int dx[4]={0,0,-1,1}; int dy[4]={-1,1,0,0}; void dfs(int x,int y){ if(f[x][y]=='#'){ return ; } f[x][y]='#'; ans++; for(int i=0;i<4;i++){ int nx=x+dx[i]; int ny=y+dy[i]; if(f[nx][ny]=='.'&&nx>0&&nx<=m&&ny>0&&ny<=n){ dfs(nx,ny); } } } int main(){ cin>>n>>m; for(int i=1;i<=m;i++){ for(int j=1;j<=n;j++){ cin>>f[i][j]; } } for(int i=1;i<=m;i++){ for(int j=1;j<=n;j++){ if(f[i][j]=='@'){ dfs(i,j); } } } cout<<ans; return 0; }
- 1
Information
- ID
- 1233
- Time
- 1000ms
- Memory
- 128MiB
- Difficulty
- 4
- Tags
- # Submissions
- 175
- Accepted
- 80
- Uploaded By