對於這題本人剛開始的時候覺得應該用DFS來解決實現這個問題,但由於本人對於DFS並不是太熟,所以就放棄了這個想法;
但又想了想要按照這個要求實現問題則必須是黑白相間,然後把是字符是'B'或'W'改為'-',即可;
下面貼一下我的代碼吧
1 #include<cstdio>
2 #include<cstring>
3 #include<algorithm>
4 #define N 100+10
5 using namespace std;
6
7 char maze[N][N];
8 char str[N][N];
9 int n,m;
10
11 int main(void)
12 {
13 while(~scanf("%d%d",&n,&m))
14 {
15 memset(str,0,sizeof(str));
16 for(int i=0;i<n;++i)
17 scanf("%s",maze[i]);
18 for(int i=0;i<n;++i)
19 for(int j=0;j<m;++j){
20 if(maze[i][j]=='-')
21 str[i][j] = '-';
22 else{
23 if((i+j)%2==1) str[i][j]='B';
24 else str[i][j]='W';
25 }
26 }
27 for(int i=0;i<n;++i){
28 for(int j=0;j<m;++j)
29 printf("%c",str[i][j]);
30 printf("\n");
31 }
32 }
33
34 return 0;
35 }
下面我再插入本人從其他大神的博客上復制的有關於DFS解決這題的代碼:
1 #include <cstdio>
2 #include <iostream>
3 #include <algorithm>
4 using namespace std;
5
6 int n,m;
7 char Map[110][110];
8 int Dir[][2]={{0,1},{0,-1},{-1,0},{1,0}};
9 void DFS(int x,int y,int num)
10 {
11 if(num==0)
12 {
13 Map[x][y]='W';
14 }
15 else
16 {
17 Map[x][y]='B';
18 }
19 int Fx,Fy;
20 for(int i=0;i<4;i++)
21 {
22 Fx=x+Dir[i][0];
23 Fy=y+Dir[i][1];
24 if(Fx>=0&&Fx<n&&Fy>=0&&Fy<m&&Map[Fx][Fy]=='.')
25 {
26 if(num==0)
27 {
28 DFS(Fx,Fy,1);
29 }
30 else
31 {
32 DFS(Fx,Fy,0);
33 }
34 }
35 }
36 }
37 int main()
38 {
39 scanf("%d %d",&n,&m);
40 for(int i=0;i<n;i++)
41 {
42 scanf("%s",Map[i]);
43 }
44 for(int i=0;i<n;i++)
45 {
46 for(int j=0;j<m;j++)
47 {
48 if(Map[i][j]=='.')
49 {
50 DFS(i,j,0);
51 }
52 }
53 }
54 for(int i=0;i<n;i++)
55 {
56 printf("%s\n",Map[i]);
57 }
58 return 0;
59 }
