-
Notifications
You must be signed in to change notification settings - Fork 0
/
nat.cpp
113 lines (110 loc) · 2.14 KB
/
nat.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
#include<iostream>
#include<queue>
using namespace std;
int ans = 0;
bool check(int sx,int sy,int m,int n,char ch[105][105])
{
if(sx >= 0 && sx < m && sy >= 0 && sy < n) {
if(ch[sx][sy] == '*' ) {
return false;
}else if(ch[sx][sy] == 'O' || ch[sx][sy] == '#'){
return true;
}
}else {
return false;
}
}
int bfs(int a[105][105],char ch[105][105],int sx,int sy,int dx,int dy,int m,int n)
{
int vis[105][105] = {0};
queue<int> q1;
q1.push(sx);
q1.push(sy);
vis[sx][sy] = 1;
while(!q1.empty()) {
int u = q1.front();
q1.pop();
int v = q1.front();
q1.pop();
cout << "poped values are " << u << " and " << v << endl;
if(check(sx-1,sy,m,n,ch)) {
if(vis[sx-1][sy] == 0 || a[sx-1][sy] > a[sx][sy] + 1) {
q1.push(sx-1);
q1.push(sy);
a[sx-1][sy] = a[sx][sy] + 1;
vis[sx-1][sy] = 1;
}
}
if(check(sx+1,sy,m,n,ch)) {
if(vis[sx+1][sy] == 0 || a[sx+1][sy] > a[sx][sy] + 1) {
q1.push(sx+1);
q1.push(sy);
a[sx+1][sy] = a[sx][sy] + 1;
vis[sx+1][sy] = 1;
}
}
if(check(sx,sy-1,m,n,ch)) {
if(vis[sx][sy-1] == 0 || a[sx][sy-1] > a[sx][sy] + 1) {
q1.push(sx);
q1.push(sy-1);
a[sx][sy-1] = a[sx][sy] + 1;
vis[sx][sy-1] = 1;
}
}
if(check(sx,sy+1,m,n,ch)) {
if(vis[sx][sy+1] == 0 || a[sx][sy+1] > a[sx][sy] + 1) {
q1.push(sx);
q1.push(sy+1);
a[sx][sy+1] = a[sx][sy] + 1;
vis[sx][sy+1] = 1;
}
}
}
if(q1.empty()) {
if(a[dx][dy] != 100000) {
return a[dx][dy];
}else {
return -1;
}
}
}
int main()
{
int t;
cin >> t;
while(t--) {
int a[105][105];
for(int i = 0;i < 105;i++) {
for(int j = 0;j < 105;j++) {
a[i][j] = 100000;
}
}
int n,m,sx,sy,dx,dy;
cin >> m >> n;
char ch[105][105];
for(int i = 0;i < m;i++) {
for(int j = 0;j < n;j++) {
cin >> ch[i][j];
if(ch[i][j] == '$') {
sx = i;
sy = j;
}
if(ch[i][j] == '#') {
dx = i;
dy = j;
}
}
}
a[sx][sy] = 0;
//cout << sx << sy << dx << dy << endl;
int temp = bfs(a,ch,sx,sy,dx,dy,m,n);
for(int i = 0;i < m;i++) {
for(int j = 0;j < n;j++) {
cout << a[i][j] << " ";
}
cout << endl;
}
cout << temp << endl;
}
return 0;
}