#include <cstdio>
#include <iostream>
#include <queue>
using namespace std;
const int maxn = 1002;
int m, n, ans = 0;
bool court[maxn][maxn], vis[maxn][maxn];
char c;
priority_queue<int> x;
priority_queue<int> y;
void dfs(int curY, int curX) {
vis[curY][curX] = true;
x.push(curX);
y.push(curY);
if(!vis[curY + 1][curX] && court[curY + 1][curX]) //not visited and true
dfs(curY + 1, curX);
if(!vis[curY - 1][curX] && court[curY - 1][curX])
dfs(curY - 1, curX);
if(!vis[curY][curX + 1] && court[curY][curX + 1])
dfs(curY, curX + 1);
if(!vis[curY][curX - 1] && court[curY][curX - 1])
dfs(curY, curX - 1);
return;
}
bool isShip() {
int lastX = x.top(), lastY = y.top();
x.pop();
y.pop();
bool first = true;
for(int maxY = 0, cnt = 0; !x.empty(); x.pop() ) { //cnt--recall maxY
cnt++;
if(lastX != x.top() ) {
lastX = x.top();
if(first) {
first = false;
maxY = cnt;
}
else {
if(cnt != maxY)
return false;
}
cnt = 0;
}
}
first = true;
for(int maxX = 0, cnt = 0; !y.empty(); y.pop() ) { //cnt--recall maxY
cnt++;
if(lastY != y.top() ) {
lastY = y.top();
if(first) {
first = false;
maxX = cnt;
}
else {
if(cnt != maxX)
return false;
}
cnt = 0;
}
}
return true;
}
int main() {
//init
scanf("%d%d", &n, &m);
for(int i = 1; i <= n; i++)
for(int j = 1; j <= m; j++) {
cin >> c;
if(c == '#') //turn to bool
court[i][j] = true;
else
court[i][j] = false;
}
for(int i = 1; i <= n; i++)
for(int j = 1; j <= m; j++)
if(court[i][j] && !vis[i][j] ) { //if true here
dfs(i, j);
if(isShip() )
ans++;
}
if(!ans)
printf("Bad placement.");
else
printf("There are %d ships.", ans);
return 0;
}
在最后的时候,我的判定是:若ans为0,则输出“Bad-”,然而题意申明:一旦有无效船只就输出“Bad-”。也就是说,我的代码里,无论有没有无效船只,只要有有效船就输出答案,与题意违背,但是这段代码却只带来了1个WA而且还是特判