質問編集履歴
1
ソースを全部載せました
title
CHANGED
File without changes
|
body
CHANGED
@@ -18,12 +18,88 @@
|
|
18
18
|
|
19
19
|
```ここに言語名を入力java
|
20
20
|
ソースコード
|
21
|
+
import java.util.Scanner;
|
22
|
+
import java.util.Stack;
|
23
|
+
|
24
|
+
public class Main {
|
25
|
+
static final int[] dx = { -1, 0, 1, 0 };
|
26
|
+
static final int[] dy = { 0, 1, 0, -1 };
|
27
|
+
static int N;
|
28
|
+
static char[][] map;
|
29
|
+
static String string;
|
30
|
+
|
31
|
+
public static void main(String[] args) {
|
32
|
+
// 自分の得意な言語で
|
33
|
+
// Let's チャレンジ!!
|
34
|
+
Scanner sc = new Scanner(System.in);
|
35
|
+
N = sc.nextInt();
|
36
|
+
map = new char[N][];
|
37
|
+
for(int i=0; i<N; i++){
|
38
|
+
map[i]=sc.next().toCharArray();
|
39
|
+
}
|
40
|
+
int M = sc.nextInt();
|
41
|
+
for(int i=0; i<M; i++){
|
42
|
+
string = sc.next();
|
21
|
-
int x
|
43
|
+
int x=0;
|
22
|
-
int y
|
44
|
+
int y=0;
|
23
|
-
|
45
|
+
Stack<int[]> visited = new Stack<>();
|
24
|
-
|
46
|
+
Boolean writable = false;
|
47
|
+
for(int j=0; j<N; j++){
|
48
|
+
for(int k=0; k<N; k++){
|
49
|
+
if(string.charAt(0)==map[j][k]){
|
50
|
+
y=j;
|
51
|
+
x=k;
|
25
|
-
next
|
52
|
+
int[] next = {y,x};
|
26
53
|
visited.push(next);
|
54
|
+
int count=1;
|
55
|
+
if(dfs(visited,y,x,count)){
|
56
|
+
System.out.println("yes");
|
57
|
+
writable=true;
|
58
|
+
break;
|
59
|
+
}
|
60
|
+
}
|
61
|
+
}
|
62
|
+
if(writable){
|
63
|
+
break;
|
64
|
+
}
|
65
|
+
}
|
66
|
+
if(!writable){
|
67
|
+
System.out.println("no");
|
68
|
+
}
|
69
|
+
}
|
70
|
+
}
|
71
|
+
|
72
|
+
public static boolean dfs(Stack<int[]> visited, int sh, int sw, int count){
|
73
|
+
if(count==string.length()){
|
74
|
+
return true;
|
75
|
+
}else{
|
76
|
+
for (int i = 0; i < 4; i++) {
|
77
|
+
int nw = sw + dx[i];
|
78
|
+
int nh = sh + dy[i];
|
79
|
+
int[] next = {nh, nw};
|
80
|
+
if (nw < 0 || nw >= N || nh < 0 || nh >= N) {
|
81
|
+
continue;
|
82
|
+
}else if(map[nh][nw]==string.charAt(count) && !visited.contains(next)){
|
83
|
+
visited.push(next);
|
84
|
+
count+=1;
|
85
|
+
if(dfs(visited, nh, nw, count)){
|
86
|
+
return true;
|
87
|
+
}else{
|
88
|
+
count-=1;
|
89
|
+
visited.pop();
|
90
|
+
}
|
91
|
+
}
|
92
|
+
}
|
93
|
+
return false;
|
94
|
+
}
|
95
|
+
}
|
96
|
+
}
|
97
|
+
|
98
|
+
|
99
|
+
|
100
|
+
|
101
|
+
|
102
|
+
|
27
103
|
```
|
28
104
|
|
29
105
|
### 試したこと
|