-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path65.cpp
More file actions
37 lines (33 loc) · 1.15 KB
/
65.cpp
File metadata and controls
37 lines (33 loc) · 1.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>
#include <string>
#include <vector>
using namespace std;
bool path(char *matrix, int rows, int cols, int i, int j, char *str, int k, vector<bool> flag) {
int index = i * cols + j;
if (i < 0 || i >= rows || j < 0 || j >= cols || matrix[index] != str[k] || flag[index])
return false;
if (k == strlen(str) - 1)
return true;
flag[index] = true;
if (path(matrix, rows, cols, i - 1, j, str, k + 1, flag) || path(matrix, rows, cols, i + 1, j, str, k + 1, flag) ||
path(matrix, rows, cols, i, j - 1, str, k + 1, flag) || path(matrix, rows, cols, i, j + 1, str, k + 1, flag))
return true;
flag[index] = false;
return false;
}
bool hasPath(char *matrix, int rows, int cols, char *str) {
vector<bool> flag(rows * cols, false);
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
if (path(matrix, rows, cols, i, j, str, 0, flag))
return true;
return false;
}
int main() {
ios::sync_with_stdio(false);
int rows, cols;
char s[101], str[101];
cin >> rows >> cols >> s >> str;
cout << hasPath(s, rows, cols, str);
return 0;
}