首页 > 代码库 > Problem J: Island Buses
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(1) * 4;using namespace std;char str[100][100];bool visit1[100][100];bool visit2[100][100];int cnt ;int len;int bridge;int dr[] = {1,-1,0,0};int dc[] = {0,0,-1,1};void dfs1(int r,int c){ visit1[r][c] = 1; for(int i = 0;i < 4;i++){ int xx = r + dr[i]; int yy = c + dc[i]; if(xx >= 0 && yy >= 0 && 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] = 1; for(int i = 0;i < 4;i++){ int xx = r + dr[i]; int yy = c + dc[i]; if(xx >= 0 && yy >= 0 && 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 = 0; visit2[xx][yy] = 1; bridge++; while(1){ j++; int tt1 = xx + j * dr[i]; int tt2 = yy + j * dc[i]; if(tt1 < 0 || tt2 < 0 || tt1 >= cnt || tt2 >= len) break; visit2[tt1][tt2] = 1; if(str[tt1][tt2] == ‘X‘){ dfs2(tt1,tt2); break; } } } } }}int main(){ //freopen("input.in","r",stdin); //freopen("output.in","w",stdout); cnt = 0; int cas = 1; memset(str,0,sizeof(str)); while(fgets(str[0],sizeof(str[0]),stdin) != NULL){ if(cas != 1) cout << endl; len = strlen(str[0]) - 1; while((fgets(str[++cnt],sizeof(str[0]),stdin) )!= NULL){ if(str[cnt][0] == 10){ break; } } bridge = 0; int bus = 0; int island = 0; memset(visit1,0,sizeof(visit1)); memset(visit2,0,sizeof(visit2)); for(int i = 0;i <= cnt;i++){ for(int j = 0;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 = 0; memset(str,0,sizeof(str)); } return 0;}
Problem J: Island Buses
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。