10562 - Undraw the Trees

參考博客:

http://blog.csdn.net/goomaple/article/details/7818170


自己的代碼實現:

#include<iostream>
using namespace std;

char Tree[210][210];

void DFS(int r, int c) {

	cout << Tree[r][c];
	//輸出前導左括號
	cout << "(";
	
	//如果是最後一層了
	if (Tree[r+1][0] == '#') {
		cout << ")";
		return;
	}
	else {//如果子樹不爲空
		if (Tree[r + 1][c] == '|') {
			//find where '-' start
			int s = c;
			while (true) {
				if (s == 0)break;
				else if (Tree[r + 2][s - 1] == ' ')break;
				s--;

			}
		
			//遞歸
			for (int i = s; Tree[r + 2][i] != ' '; i++)
			{
				if (Tree[r + 3][i] != ' '&&Tree[r + 3][i] != '-'
					&&Tree[r + 3][i] != '#'&&Tree[r + 3][i] != '|')
					DFS(r + 3, i);
			}
		}
		else {
			cout << ")";
			return;
		}
	}
	
	cout << ")";
	return;
}

int main() {

	FILE*ostream;
	freopen_s(&ostream, "C:\\Users\\zgwng\\Desktop\\10562.txt", "r", stdin);
	//read case
	int num;
	scanf_s("%d", &num);
	char c[210];
	gets_s(c);
	while (num--) {
		//read the tree
		int i = 0;
		while (true) {
			gets_s(Tree[i]);
			if (Tree[i][0] == '#')break;
			i++;
		}
		int c;
		for (int j = 0; j < strlen(Tree[0]); j++) {
			if (Tree[0][j] != ' '&&Tree[0][j] != '-'
				&&Tree[0][j] != '#'&&Tree[0][j] != '|')
			{
				c = j;
				break;
			}
		}
		cout << "(";
		if (i > 0)
		{
			DFS(0, c);
		}
		cout << ")";
		cout << endl;
	}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章