12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
#include<cstdio>#include<cstring>#include<queue>struct pnt{ int x, y;};using namespace std;int n, m;char s[1024][1024];const int del[6] = {0,0,1,-1,1,0};bool vis[1024][1024];bool flag;queue<pnt> q;bool legal(pnt nd) { if (nd.x >= 0 && nd.x < n && nd.y >= 0 && nd.y < m) return true; return false;}void bfs(int x, int y) { pnt p, jp; int v1 = y-1, v2 = -2, h1 = -2, h2 = -2; p.x = x; p.y = y; q.push(p); vis[x][y] = true; while (!q.empty()) { p = q.front(); q.pop(); for (int i = 0; i < 3; ++i) { jp.x = p.x+del[i]; jp.y = p.y+del[i+3]; if (legal(jp) && !vis[jp.x][jp.y] && s[jp.x][jp.y] == '#') { q.push(jp); vis[jp.x][jp.y] = true; } else if (!vis[jp.x][jp.y]){ if (i == 0) { if (v1 != jp.y) { flag = true; return; } } else if (i == 1) { if (v2 == -2) v2 = jp.y; else if (v2 != jp.y) { flag = true; return; } } else if (i == 2) { if (h2 == -2) h2 = jp.x; else if (h2 != jp.x) { flag = true; return; } } } } }}int main() { int sum; while (scanf("%d%d", &n, &m) !=EOF) { flag = false; sum = 0; memset(vis, 0, sizeof(vis)); memset(s, 0, sizeof(s)); for (int i = 0; i < n; ++i) scanf("%s", s[i]); for (int i = 0; i < n; ++i) for (int j = 0; j < m; ++j) { if (!vis[i][j]) { if (s[i][j] == '#') { bfs(i, j); if (flag){ printf("So Sad\n"); i = n; break; } sum++; } else { vis[i][j] = true; } } } if (!flag) printf("There are %d ships.\n", sum); } return 0;}
返回