[白俊](Java)1987-アルファベット
質問リンク
https://www.acmicpc.net/problem/1987
問題を解く
mapを使用して重複するアルファベットを検索します.新しいセルにアクセスするときにmapにすでに値が格納されている場合は、答えを求める値を選択して返す方法を選択します.
次のdfsを渡す前に、chkとstorageの値を変更してください.
dfsが終了して戻ると、格納値とchk値は元の値を返します.
コード#コード#
import java.sql.SQLOutput;
import java.util.*;
public class Main {
static int n;
static int m;
static String[][] map;
static int[] diry = {-1, 0, 1, 0};
static int[] dirx = {0, 1, 0, -1};
static int answer = 0;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
m = sc.nextInt();
map = new String[n][m];
Map<String, Integer> storage = new HashMap<>();
for (int i = 0; i < n; i++) {
String[] line = sc.next().split("");
map[i] = line;
}
dfs(0, 0, 1, new boolean[n][m], storage);
System.out.println(answer);
}
public static void dfs(int y, int x, int ans, boolean[][] chk, Map<String, Integer> storage) {
chk[0][0] = true;
storage.put(map[0][0],0);
for (int i = 0; i < 4; i++) {
int now_y = y + diry[i];
int now_x = x + dirx[i];
if (now_y >= 0 && now_y < n && now_x >= 0 && now_x < m) {
if (!chk[now_y][now_x]) {
if (!storage.containsKey(map[now_y][now_x])) {
chk[now_y][now_x] = true;
storage.put(map[now_y][now_x], 0);
dfs(now_y, now_x, ans + 1, chk, storage);
storage.remove(map[now_y][now_x]);
chk[now_y][now_x] = false;
} else {
answer = Math.max(answer, ans);
}
} else {
answer = Math.max(answer, ans);
}
}
}
return;
}
}
Reference
この問題について([白俊](Java)1987-アルファベット), 我々は、より多くの情報をここで見つけました https://velog.io/@courage331/백준Java-1987-알파벳テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol