首先我是这么写的:
#include <iostream>
#include <string>
using namespace std;
char maps[114][210];
bool is_used[114][210];
int shifts[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
int ans;
int n;
string in;
void dfs(int x, int y){
for(int i=0; i<4; i++){
int nowx = x + shifts[i][0];
int nowy = y + shifts[i][1];
if(nowx>=1 and nowy>=1 and maps[nowx][nowy]>='a' and maps[nowx][nowy]<='z' and !is_used[nowx][nowy]){
is_used[nowx][nowy] = true;
dfs(nowx, nowy);
}
}
}
int main(){
cin >> n;
getchar();
for(int i=1; i<=n; i++){
getline(cin, in);
int len = in.length();
for(int j=0; j<len; j++){
maps[i][j+1] = in[j];
}
}
for(int i=1; i<=105; i++){
for(int j=1; j<=205; j++){
if(!is_used[i][j] and maps[i][j]>='a' and maps[i][j]<='z'){
is_used[i][j] = true;
ans++;
dfs(i, j);
}
}
}
cout << ans;
}
AC 2, 6, 8, 10, 得40分.
于是我去看讨论区, 发现要用scanf("\n").
于是写出如下代码:
#include <iostream>
#include <string>
using namespace std;
char maps[114][210];
bool is_used[114][210];
int shifts[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
int ans;
int n;
string in;
void dfs(int x, int y){
for(int i=0; i<4; i++){
int nowx = x + shifts[i][0];
int nowy = y + shifts[i][1];
if(nowx>=1 and nowy>=1 and maps[nowx][nowy]>='a' and maps[nowx][nowy]<='z' and !is_used[nowx][nowy]){
is_used[nowx][nowy] = true;
dfs(nowx, nowy);
}
}
}
int main(){
cin >> n;
scanf("\n");
for(int i=1; i<=n; i++){
getline(cin, in);
int len = in.length();
for(int j=0; j<len; j++){
maps[i][j+1] = in[j];
}
}
for(int i=1; i<=105; i++){
for(int j=1; j<=205; j++){
if(!is_used[i][j] and maps[i][j]>='a' and maps[i][j]<='z'){
is_used[i][j] = true;
ans++;
dfs(i, j);
}
}
}
cout << ans;
}
AC 1, 4, 5, 6, 7, 9, 得60分.
很气愤, 为什么连点2都过不了?
于是再敲了一个getchar()
#include <iostream>
#include <string>
using namespace std;
char maps[114][210];
bool is_used[114][210];
int shifts[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
int ans;
int n;
string in;
void dfs(int x, int y){
for(int i=0; i<4; i++){
int nowx = x + shifts[i][0];
int nowy = y + shifts[i][1];
if(nowx>=1 and nowy>=1 and maps[nowx][nowy]>='a' and maps[nowx][nowy]<='z' and !is_used[nowx][nowy]){
is_used[nowx][nowy] = true;
dfs(nowx, nowy);
}
}
}
int main(){
cin >> n;
getchar();getchar();
for(int i=1; i<=n; i++){
getline(cin, in);
int len = in.length();
for(int j=0; j<len; j++){
maps[i][j+1] = in[j];
}
}
for(int i=1; i<=105; i++){
for(int j=1; j<=205; j++){
if(!is_used[i][j] and maps[i][j]>='a' and maps[i][j]<='z'){
is_used[i][j] = true;
ans++;
dfs(i, j);
}
}
}
cout << ans;
}
然后, 过了...???
求求各位dalao给出理由为什么会出现这样的情况.
所有测试皆使用c++14(gcc 9)标准.