1 条题解

  • 0
    @ 2023-6-11 12:22:25

    C++ :

    #include<bits/stdc++.h>
    #define R register
    using namespace std;
    int w,h,s1,s2;
    char a[120][120];
    int sum;
    void dfs(int x,int y){
        if(x<1||y<1||x>h||y>w||a[x][y]=='#')
    		return;
    	sum++;	
    	a[x][y]='#';
    	dfs(x+1,y);
    	dfs(x-1,y);
    	dfs(x,y-1);
    	dfs(x,y+1);
    }
    template <typename T> void read(T &t){
    	t=0;
    	char ch=getchar();
    	int f=1;
    	while(ch<'0'||ch>'9'){
    		if(ch=='-')f=-1;
    		ch=getchar();
    	}
    	do{
    		(t*=10)+=ch-'0';
    		ch=getchar();
    	}while(ch>='0'&&ch<='9');
    	t*=f;
    }
    int main(){
    		sum=0;
    		read(w);
    		read(h);
    		for(R int i=1;i<=h;i++){
    			for(R int j=1;j<=w;j++){
    				cin>>a[i][j];
    				if(a[i][j]=='@'){
    					s1=i;
    					s2=j;
    				}
    			}
    		}
            dfs(s1,s2);
            printf("%d\n",sum);
    	return 0;
    }
    
    

    Python :

    def dfs(x,y):
        b[x][y]=1
        a[x][y]="#"
        for i in range(4):
            tx=x+tr[i][0]
            ty=y+tr[i][1]
            if(tx>=0 and tx<h and ty>=0 and ty<w):
                if(b[tx][ty]==0 and a[tx][ty]=="."):
                    dfs(tx,ty)
        return
    sr=input().split()
    w=int(sr[0])
    h=int(sr[1])
    a=[[0 for i in range(w)] for j in range(h)]
    b=[[0 for i in range(w)] for j in range(h)]
    tr=[[-1,0],[1,0],[0,-1],[0,1]]
    x=0
    y=0
    for i in range(h):
        sr=input()
        for j in range(w):
            a[i][j]=sr[j:j+1]
            if(a[i][j]=="@"):
                x=i
                y=j
    dfs(x,y)
    k=0
    for i in range(h):
        for j in range(w):
            if(b[i][j]==1):
                k=k+1
    print(k)
    
    
    • 1

    信息

    ID
    2767
    时间
    1000ms
    内存
    128MiB
    难度
    (无)
    标签
    递交数
    0
    已通过
    0
    上传者