import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
private static int answer =0;
private static boolean[][] visit;
private static char[][] map;
private static int x, y, k;
private static int[] dx = {1, 0, -1, 0};
private static int[] dy = {0, -1, 0, 1};
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
x = Integer.parseInt(st.nextToken());
y = Integer.parseInt(st.nextToken());
k = Integer.parseInt(st.nextToken());
visit = new boolean[x][y];
map = new char[x][y];
for(int i=0; i<x;i++){
st = new StringTokenizer(br.readLine());
String str = st.nextToken();
for(int j=0; j<y;j++){
map[i][j] = str.charAt(j);
}
}
dfs(x-1, 0, 1);
System.out.println(answer);
}
public static void dfs(int curX, int curY, int count ){
if(count == k){
if(curX == 0 && curY == y-1){
answer++;
}
return;
}
for(int i=0; i<4; i++){
int newX = curX+dx[i];
int newY = curY+dy[i];
if(newX < x && newY < y && newY >=0 && newX >=0
&& map[newX][newY] !='T' ){
if(!visit[newX][newY]){
visit[newX][newY] = true;
dfs(newX, newY, count+1);
visit[newX][newY]= false;
}
}
}
}
}
틀린이유 이며 아래를 시작하기 전에 추가해야하는이유
visit[x-1][0] = true;
dfs(x-1, 0, 1);
시작하는 지점으로 1을 추가해서 시작한다.
현재지점을 우측으로 갔다가 좌측으로 올수도 있다는 것이다.그러니까 출발 지점의 방문 여부도 체크해줘야한다.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
private static int answer =0;
private static boolean[][] visit;
private static char[][] map;
private static int x, y, k;
private static int[] dx = {1, 0, -1, 0};
private static int[] dy = {0, -1, 0, 1};
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
x = Integer.parseInt(st.nextToken());
y = Integer.parseInt(st.nextToken());
k = Integer.parseInt(st.nextToken());
visit = new boolean[x][y];
map = new char[x][y];
for(int i=0; i<x;i++){
st = new StringTokenizer(br.readLine());
String str = st.nextToken();
for(int j=0; j<y;j++){
map[i][j] = str.charAt(j);
}
}
visit[x-1][0] = true;
dfs(x-1, 0, 1);
System.out.println(answer);
}
public static void dfs(int curX, int curY, int count ){
if(count == k){
if(curX == 0 && curY == y-1){
answer++;
}
return;
}
for(int i=0; i<4; i++){
int newX = curX+dx[i];
int newY = curY+dy[i];
if(newX < x && newY < y && newY >=0 && newX >=0
&& map[newX][newY] !='T' ){
if(!visit[newX][newY]){
visit[newX][newY] = true;
dfs(newX, newY, count+1);
visit[newX][newY]= false;
}
}
}
}
}