fork(2) download
  1. #include<stdio.h>
  2.  
  3. int dx[] = { 1,-1, 0, 0 };
  4. int dy[] = { 0, 0, 1,-1 };
  5. int n,m;
  6. char visited[1001][1001];
  7. char Cell[1001][1001];
  8.  
  9. int isSafe(int x, int y)
  10. {
  11. return ( (x>=0 && y>=0 && x<n && y<m) && (Cell[x][y]=='b' || Cell[x][y]=='f') && visited[x][y]==0 );
  12. }
  13.  
  14. int Dfs(int x,int y)
  15. {
  16. //visited[x][y] = 1;
  17. int dir,xx,yy;
  18. if(Cell[x][y] == 'f') return 1;
  19. for(dir=0; dir<4; dir++)
  20. {
  21. xx = x+dx[dir], yy = y+dy[dir];
  22. if( isSafe(xx,yy) )
  23. {
  24. visited[x][y] = 1;
  25. if( Dfs(xx,yy) ) { Cell[x][y] = '-'; return 1; }
  26. }
  27. }
  28. return 0;
  29. }
  30.  
  31. int main()
  32. {
  33. int i,j,x,y,T;
  34. scanf("%d",&T);
  35. while(T--)
  36. {
  37. scanf("%d%d",&n,&m);
  38. for(i=0; i<n; i++)
  39. for(j=0; j<m; j++)
  40. visited[i][j] = 0;
  41.  
  42. for(i=0; i<n; i++) scanf("%s",&Cell[i]);
  43.  
  44. for(i=0; i<n; i++)
  45. for(j=0; j<m; j++)
  46. if(Cell[i][j] == 's') { x=i; y=j; break; }
  47.  
  48. //visited[x][y] = 1;
  49. if( Dfs(x,y) )
  50. {
  51. for(i=0; i<n; i++)
  52. {
  53. for(j=0; j<m;j++)
  54. {
  55. if( Cell[i][j] == '-') Cell[i][j] = 'b' ;
  56. else if( Cell[i][j] == 'w' || Cell[i][j] == 'b' ) Cell[i][j] = '-' ;
  57. }
  58. }
  59. Cell[x][y] = 's';
  60. for(i=0; i<n; i++) printf("%s\n",Cell[i]);
  61. }
  62. else printf("The path doesn't exist.\n");
  63. }
  64. return 0;
  65. }
Success #stdin #stdout 0s 4812KB
stdin
1
7 7
wwwwwww
wfbwbbw
wbwwwbw
wbbbbbw
wwwwwbw
wwwwwsw
wwwwwww
stdout
-------
-f-----
-b-----
-bbbbb-
-----b-
-----s-
-------