Description 求連通分量地區座標集合
Input 多組輸入,每組形式見下。 n m startPointX startPointY 代表n行m列的地圖(從一計數) 尋找連通分量的起始點為(startPointX ,startPointY)(從0計數)
|------->x座標 | | | 向下為y座標
然後為n行m列的字元。'a'表示障礙,'b'表示可求連通分量的有效地區。
以0 0結束輸入 Output 連通分量地區座標集合
sampleInput 5 3
1 2
abb
aaa
bbb
bbb
bab
4 4
2 1
aaaa
aaba
abba
aaaa
5 3
1 0
abb
aaa
bbb
bbb
bab
0 0
sampleOutput (1,2) (2,2) (2,3) (1,3) (0,3) (0,4) (0,2) (2,4)
(2,1) (2,2) (1,2)
(1,0) (2,0)
#include #include #include#includeusing namespace std;#define SIZE 10char maze[SIZE][SIZE];int n,m;//n rows,m columnsint go[][2]={1,0,-1,0,0,1,0,-1};//狀態轉移矩陣 ,往右,往左,往下,往上struct node{ int x,y;}; bool operator == (const node& a,const node& b ){ return a.x==b.x && a.y==b.y;}node startNode;vector v;void f_DFS(node newNode){ node nextNode;for(int i=0;i<4;i++){nextNode.x=newNode.x+go[i][0];nextNode.y=newNode.y+go[i][1];if(nextNode.x<0|| nextNode.x>=m || nextNode.y<0 || nextNode.y>=n) //若下一位置超出地圖外 continue;if(maze[nextNode.y][nextNode.x]=='a') //若下一位置是障礙 continue; if(find(v.begin(),v.end(),nextNode)!=v.end()) // 若已經訪問過 continue; else{ v.push_back(nextNode); f_DFS(nextNode); }}//for}void f_init(){ v.clear();}void f_read(){ cin>>startNode.x>>startNode.y; v.push_back(startNode);for(int i=0;i>maze[i][j]; if(maze[startNode.y][startNode.x]=='a'){ cout<<"資料不合法";exit(-100); }}void f_calc(){f_DFS(startNode);}void f_show(){ for(auto &x : v) cout<<"("<>n>>m){if(n==0||m==0 ){ //程式結束 break;} f_init(); f_read(); f_calc(); f_show(); } //whilereturn 0;}