1. 程式人生 > >uva 10562 Undraw the trees(看圖寫樹)

uva 10562 Undraw the trees(看圖寫樹)

思路:先將圖儲存在二維陣列,然後對圖進行DFS。先找到根節點,然後找根節點的子節點,對子節點DFS。

import java.util.Arrays;
import java.util.Scanner;

public class Main {

	static int maxn = 200;
	static char[][] G = new char[maxn+5][maxn+5];
	static int cnt = 0;
	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		int t = scan.nextInt();
		scan.nextLine();
		while(t--!=0){
			for(int i=0;i<maxn;i++){
				Arrays.fill(G[i], ' ');
			}
			cnt = 0;
			while(true){
				String str = scan.nextLine();
				if("#".equals(str))break;
				for(int i=0;i<str.length();i++){
					G[cnt][i] = str.charAt(i);
				}
				cnt++;
			}
			
			
			int c = -1;
			for(int i=0;i<maxn;i++){
				if(G[0][i]!=' '){
					c = i;
					break;
				}
			}
			System.out.print("(");
			if(c!=-1){
				dfs(0,c);	
			}
			System.out.print(")\n");
		}
	}
	
	public static void dfs(int r,int c){
		System.out.printf("%c(",G[r][c]);
		if(r+1<cnt&&G[r+1][c]=='|'){
			int i = c;
			while(i-1>=0&&G[r+2][i-1]=='-')i--;
			while(G[r+2][i]=='-'){
				if(G[r+3][i]!=' ')dfs(r+3,i);
				i++;
			}
		}
		System.out.printf(")");
	}
}