### 题目描述

0 0 0 0 0 0
0 0 1 1 1 1
0 1 1 0 0 1
1 1 0 0 0 1
1 0 0 0 0 1
1 1 1 1 1 1

0 0 0 0 0 0
0 0 1 1 1 1
0 1 1 2 2 1
1 1 2 2 2 1
1 2 2 2 2 1
1 1 1 1 1 1


### 输入格式

//感谢黄小U饮品指出本题数据和数据格式不一样. 已修改(输入格式)

### 输入输出样例

6
0 0 0 0 0 0
0 0 1 1 1 1
0 1 1 0 0 1
1 1 0 0 0 1
1 0 0 0 0 1
1 1 1 1 1 1


0 0 0 0 0 0
0 0 1 1 1 1
0 1 1 2 2 1
1 1 2 2 2 1
1 2 2 2 2 1
1 1 1 1 1 1


1 \le n \le 30

### 题解

  1 #include <iostream>
2 #include <stdio.h>
3 #include <math.h>
4 #include <algorithm>
5 #include <string.h>
6
7 using namespace std;
8
9 const int MAXN = 105;
10 int n, map[MAXN][MAXN], vis[MAXN][MAXN];
11 int pos[4][2] = {0, 1, 0, -1, 1, 0, -1, 0};
12
13 struct Node
14 {
15     int x, y;
16 };
17
18 Node q[MAXN];
19 int front, rear;
20 int a, b;
21
22 void bfs()
23 {
24     Node now;
25     now.x = a;
26     now.y = b;
27     if(map[a][b] != 2)
28     {
29         return;
30     }
31     front = rear = 0;
32     q[rear] = now;
33     rear++;
34     while(front < rear)
35     {
36         now = q[front++];
37         if(map[now.x][now.y] == 2)
38         {
39             map[now.x][now.y] = 0;
40         }
41         if(now.x == 7)
42         {
43             now.x = 7;
44         }
45         for(int i = 0; i < 4; i++)
46         {
47             int nx = now.x + pos[i][0];
48             int ny = now.y + pos[i][1];
49             if(nx <= n && nx > 0 && ny <= n && ny > 0
50                 && vis[nx][ny] == false
51                 && map[nx][ny] == 2)
52             {
53                 map[nx][ny] = 0;
54                 vis[nx][ny] = true;
55                 q[rear].x = nx;
56                 q[rear].y = ny;
57                 rear++;
58             }
59         }
60     }
61 }
62
63
64 int main()
65 {
66     cin >> n;
67     for(int i = 1; i <= n; i++)
68     {
69         for(int j = 1; j <= n; j++)
70         {
71             cin >> map[i][j];
72             if(map[i][j] == 0)
73             {
74                 map[i][j] = 2;
75             }
76         }
77     }
78     for(int i = 1; i <= n; i++)
79     {
80         a = 1;
81         b = i;
82         bfs();
83     }
84     for(int i = 1; i <= n; i++)
85     {
86         a = n;
87         b = i;
88         bfs();
89     }
90     for(int i = 1; i <= n; i++)
91     {
92         a = i;
93         b = 1;
94         bfs();
95     }
96     for(int i = 1; i <= n; i++)
97     {
98         a = i;
99         b = n;
100         bfs();
101     }
102     for(int i = 1; i <= n; i++)
103     {
104         for(int j = 1; j <= n; j++)
105         {
106             cout << map[i][j] << " ";
107         }
108         cout << endl;
109     }
110     return 0;
111 }

posted on 2019-08-24 13:41 zealsoft 阅读(...) 评论(...) 编辑 收藏