Problem J: Island Buses

主要题意是:大海之间有岛,有的岛之间有桥,问你岛的个数,桥的个数,以及没有桥联通岛的个数,其中最后一次输入的没有回车,不注意的话最后一次会被吞,第二,桥的两端的标记是“X”(X也代表陆地),“X”的四周都可以有“B”形成的桥,一开始没写好,后来根据“X”标记所有的桥只能走一次然后标记……总之,虽然是水题,写出来还是蛮开心的……

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <map>
#include <cmath>
#include <cstring>
#include <string>
#include <queue>
#include <stack>
#include <cctype> const double Pi = atan() * ;
using namespace std;
char str[][];
bool visit1[][];
bool visit2[][];
int cnt ;
int len;
int bridge;
int dr[] = {,-,,};
int dc[] = {,,-,};
void dfs1(int r,int c){
visit1[r][c] = ;
for(int i = ;i < ;i++){
int xx = r + dr[i];
int yy = c + dc[i];
if(xx >= && yy >= && xx < cnt && yy < len){
if(!visit1[xx][yy] && (str[xx][yy] == '#' || str[xx][yy] == 'X' )){
dfs1(xx,yy);
}
}
}
}
void dfs2(int r,int c){
visit2[r][c] = ;
for(int i = ;i < ;i++){
int xx = r + dr[i];
int yy = c + dc[i];
if(xx >= && yy >= && xx < cnt && yy < len){
if(!visit2[xx][yy] && (str[xx][yy] == '#' || str[xx][yy] == 'X')){
dfs2(xx,yy);
}
else if(str[xx][yy] == 'B' && str[r][c] == 'X' && !visit2[xx][yy]){
int j = ;
visit2[xx][yy] = ;
bridge++;
while(){
j++;
int tt1 = xx + j * dr[i];
int tt2 = yy + j * dc[i];
if(tt1 < || tt2 < || tt1 >= cnt || tt2 >= len)
break;
visit2[tt1][tt2] = ;
if(str[tt1][tt2] == 'X'){
dfs2(tt1,tt2);
break;
}
}
}
}
}
}
int main()
{
//freopen("input.in","r",stdin);
//freopen("output.in","w",stdout);
cnt = ;
int cas = ;
memset(str,,sizeof(str));
while(fgets(str[],sizeof(str[]),stdin) != NULL){
if(cas != )
cout << endl;
len = strlen(str[]) - ;
while((fgets(str[++cnt],sizeof(str[]),stdin) )!= NULL){
if(str[cnt][] == ){
break;
}
}
bridge = ;
int bus = ;
int island = ;
memset(visit1,,sizeof(visit1));
memset(visit2,,sizeof(visit2));
for(int i = ;i <= cnt;i++){
for(int j = ;j < len;j++){
if( (str[i][j] == '#' || str[i][j] == 'X') && !visit1[i][j]){
island++;
dfs1(i,j);
}
if( (str[i][j] == '#' || str[i][j] == 'X')&& !visit2[i][j]){
bus++;
dfs2(i,j);
}
}
}
cout << "Map " << cas++ << endl;
cout << "islands: " << island << endl;
cout << "bridges: " << bridge << endl;
cout << "buses needed: " << bus << endl;
cnt = ;
memset(str,,sizeof(str));
}
return ;
}
上一篇:数组升序排序的方法Arrays.sort();的应用


下一篇:python filter函数应用,过滤字符串