2 条题解

  • 0
    @ 2023-11-8 16:29:42
    #include <bits/stdc++.h>
    using namespace std;
    int width,hidit,cnt;
    int x,y;
    char a[25][25];
    int dh[4]={-1,0,1,0};
    int dl[4]={0,1,0,-1};
    void dfs(int h,int l){
    	if (h==0||l==0||h>hidit||l>width){
    		return;
    	}
    	a[h][l]='#'; 
    	cnt++;
    	for(int i=0;i<4;i++){
    		if (a[h+dh[i]][l+dl[i]]=='.'){
    			dfs(h+dh[i],l+dl[i]);
    		}
    	}
    }
    int main(){
    	while(cin>>width>>hidit&&width!=0&&hidit!=0){
    		for(int i=1;i<=hidit;i++){
    			for(int j=1;j<=width;j++){
    				cin>>a[i][j];
    				if (a[i][j]=='@'){
    					x=i;
    					y=j;
    				}
    			}
    		}
    		dfs(x,y);
    		cout<<cnt<<endl;
    		cnt=0;
    	} 
    	return 0;
    }
    

    只供参考

    • 0
      @ 2022-12-7 8:44:02

      这道题的标题竟是"红与黑"(不过与"红"有什么关系啊)……

      作为资深柯迷,我第一反应是柯南的红与黑的对决篇……

      言归正传,这道题我觉得没必要用广搜,毕竟又不是走迷宫,最短路径之类的题。

      所以,上深搜代码:

      #include <bits/stdc++.h>
      using namespace std;
      int w , h  , ans , b[25][25] , startx , starty , next[4][2] = {{1 , 0} , 
                                                                     {0 , 1} , 
                                                                     {-1 , 0} , 
                                                                     {0 , -1}};
      char m[25][25];                                                
      void dfs(int x , int y)
      {
          if ((m[x][y] == '.' || m[x][y] == '@') && b[x][y] == 0) ans++;
          b[x][y] = 1;
          for (int i = 0 ; i < 4 ; i++)
          {
              int tx = x + next[i][0] , ty = y + next[i][1];
              if (tx >= 1 && tx <= h && ty >= 1 && ty <= w && m[tx][ty] == '.' && b[tx][ty] == 0)
              {
                  dfs(tx , ty);
                  b[tx][ty] = 1;
              }
          }
          return;
      }
      
      int main()
      {
          cin >> w >> h;
          for (int i = 1 ; i <= h ; i++)
          {
              for (int j = 1 ; j <= w ; j++)
              {
                  cin >> m[i][j];
                  if (m[i][j] == '@')
                  {
                      startx = i;
                      starty = j;
                  }
              }
          }
          dfs(startx , starty);
          cout << ans;
          return 0;
      }
      
      • 1

      信息

      ID
      893
      时间
      1000ms
      内存
      128MiB
      难度
      3
      标签
      递交数
      48
      已通过
      25
      上传者