-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhashpath.cpp
More file actions
52 lines (48 loc) · 1.45 KB
/
hashpath.cpp
File metadata and controls
52 lines (48 loc) · 1.45 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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <iostream>
// #include <string>
#include <vector>
#include <stack>
#include <unordered_map>
#include <queue>
#include <string.h>
using namespace std;
bool hasPath(char* matrix, int rows, int cols, char* str)
{
bool *visited = new bool[rows * cols];
memset(visited, 0, rows * cols);
int lens = 0;
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
if (hasPath(matrix, rows, cols, i, j, str, lens, visited))
{
return true;
}
}
}
delete[] visited;
return false;
}
bool hasPathCore(const char* matrix, int rows, int cols, int row, int col,
const char* str, int& lens, bool* visited)
{
if(str[lens] == '\0') return true;
bool haspath = false;
if (row >= 0 && row < rows && col >= 0 && col < cols
&& matrix[row * cols + col] == str[lens]
&& !visited[row * cols + col])
{
lens++;
visited[row * cols + col] = true;
haspath = hasPathCore(matrix, rows, cols, row, col - 1, str, lens, visited)
||hasPathCore(matrix, rows, cols, row - 1, col, str, lens, visited)
||hasPathCore(matrix, rows, cols, row, col + 1, str, lens, visited)
||hasPathCore(matrix, rows, cols, row + 1, col, str, lens, visited);
if(!haspath){
lens--;
visited[row * cols + col] = false;
}
}
return haspath;
}