[swexpert] 1861. 정사각형방 (D4 , java, dfs풀기)

728x90
반응형

bfs풀 거 같은데 dfs로 해보라해서 dfs로 풀어봤다


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class Solution {
	static int t,n;
	static int[][] map;
	static int[] xpos= {0,0,1,-1};
	static int[] ypos= {1,-1,0,0};
	static int ans,cnt,place;
	
	public static void main(String[] args) throws NumberFormatException, IOException {
		
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		t=Integer.parseInt(br.readLine());
		StringTokenizer st;
		for (int tc = 1; tc <= t; tc++) {
			n=Integer.parseInt(br.readLine());
			map=new int[n][n];
			place=n*n+1;
			ans=0;
			for (int i = 0; i < n; i++) {
				st=new StringTokenizer(br.readLine());
				for (int j = 0; j < n; j++) {
					map[i][j]=Integer.parseInt(st.nextToken());
				}
			}
			
			for (int i = 0; i < n; i++) {
				for (int j = 0; j < n; j++) {
					cnt=0;
					move(i,j,1);
//					System.out.println(cnt);
					if(cnt>=ans) {
						if(cnt==ans && map[i][j]<place) {
							place=map[i][j];
						}
						if(cnt>ans) {
							place=map[i][j];
						}
						ans=cnt;
		
					}
				}
			}
			System.out.printf("#%d %d %d\n",tc,place,ans);
		}
		
	}

	private static void move(int y, int x,int curLen) {
		
		boolean possible=false;
		for (int i = 0; i < 4; i++) {
			int xx=x+xpos[i];
			int yy=y+ypos[i];
			if(xx<0 ||yy<0 ||xx>=n ||yy>=n)continue;
			if(map[yy][xx]==map[y][x]+1) {
				possible=true;
//				System.out.println(y+","+x+","+yy+","+xx);
				move(yy,xx,curLen+1);
			}
		}
		if(!possible && cnt<curLen) {
			cnt=curLen;
		}
	}
}
728x90
반응형
TAGS.

Comments