-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimprovedSmallestPath.cpp
executable file
·121 lines (95 loc) · 1.85 KB
/
improvedSmallestPath.cpp
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
#include<iostream>
#include<cmath>
using namespace std;
char **table;
int **len;
int N = 0;
void getElement(int i,int j,int &result)
{
if(i < 0 || j < 0 || i > N-1 || j > N-1)
return;
else
if(len[i][j] == -1)
return;
else
if(len[i][j] < result)
result = len[i][j];
}
void dfs(int i, int j,int result)
{
if(i < 0 || j < 0 || i > N-1 || j > N-1 || table[i][j] == 'T' || table[i][j] == 'E')
return;
getElement(i-1,j,result);
getElement(i,j-1,result);
getElement(i,j+1,result);
getElement(i+1,j,result);
cout<<result<<"\t";
if( len[i][j] != 999999 && abs(result - len[i][j]) <= 1)
return;
len[i][j] = result + 1;
dfs(i-1,j,len[i][j] + 1);
dfs(i,j-1,len[i][j] + 1);
dfs(i, j+1,len[i][j] + 1);
dfs(i+1,j,len[i][j] + 1);
}
int main()
{
cin>>N;
table = new char*[N];
len = new int*[N];
for(int i = 0 ; i < N;i++)
{
table[i] = new char[N];
len[i] = new int[N];
}
int starti,startj,endi,endj;
for(int i = 0 ; i < N;i++)
for(int j = 0 ; j < N; j++)
len[i][j] = 999999;
for(int i = 0 ; i < N;i++)
for(int j = 0 ; j < N; j++)
{
cin>>table[i][j];
if(table[i][j] == 'S')
{
starti = i;
startj = j;
}
if(table[i][j] == 'E')
{
endi = i;
endj = j;
}
}
int temp =0;
dfs(starti,startj,temp);
for(int i = 0 ; i < N ;i++)
{
for(int j = 0 ; j < N; j++)
{
cout<<table[i][j] <<"\t";
}
cout<<"\n";
}
for(int i = 0 ; i < N;i++)
{
for(int j = 0 ; j < N; j++)
{
cout<<len[i][j] <<"\t";
}
cout<<"\n";
}
int result = 999999;
getElement(endi-1,endj,result);
getElement(endi,endj-1,result);
getElement(endi+1,endj,result);
getElement(endi,endj+1,result);
cout<<result;
for(short i = 0; i < N; ++i){
delete[] table[i];
delete[] len[i];
}
delete[] table;
delete[] len;
return 0;
}