[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
반응형
'swexpert' 카테고리의 다른 글
[swexpert] 1223. 계산기2 (java, D4) (0) | 2021.02.05 |
---|---|
[swexpert] 3499. 퍼펙트 셔플 (JAVA, D3) (0) | 2021.02.05 |
[swexpert] 5432. 쇠막대기 자르기 (JAVA) (0) | 2021.02.04 |
[swexpert] 11387. 몬스터사냥 (java) (0) | 2021.02.03 |
[swexpert] 1873. 상호의 배틀 필드 (java) (0) | 2021.02.03 |
TAGS.