1 #include <bits/stdc++.h> 2 3 using namespace std; 4 5 struct Node 6 { 7 int r,c,g; 8 Node(int r,int c,int g): r(r),c(c),g(g) {} 9 Node() {} 10 }; 11 12 int m[22][22]; 13 14 int rt,ct; 15 int k; 16 void read() 17 { 18 memset(m,0,sizeof(m)); 19 cin >> rt >> ct >> k; 20 for(int i = 0;i < rt;i ++) 21 for(int j = 0; j < ct;j ++) 22 cin >> m[i][j]; 23 } 24 25 const int dr[] = {1,0,0,-1}; 26 const int dc[] = {0,1,-1,0}; 27 28 int d[22][22][22]; 29 bool limit(Node v) 30 { 31 return v.r>=0&&v.r<rt&&v.c>=0&&v.c<ct&&v.g<=k; 32 } 33 int solve() 34 { 35 memset(d,-1,sizeof(d)); 36 queue<Node> q; 37 q.push(Node(0,0,m[0][0])); 38 d[0][0][m[0][0]] = 0; 39 while(!q.empty()) 40 { 41 Node u = q.front();q.pop(); 42 if(u.r==rt-1&&u.c==ct-1) return d[u.r][u.c][u.g]; 43 for(int i = 0; i < 4;i ++) 44 { 45 Node v = u;v.r += dr[i];v.c += dc[i]; 46 if(limit(v)&&m[v.r][v.c]==0) v.g = 0; 47 if(limit(v)&&m[v.r][v.c]==1) v.g ++; 48 if(limit(v)&&d[v.r][v.c][v.g]<0) 49 { 50 d[v.r][v.c][v.g] = d[u.r][u.c][u.g] + 1; 51 q.push(v); 52 } 53 } 54 } 55 return -1; 56 } 57 58 void print(int rnt) 59 { 60 cout << rnt << endl; 61 } 62 int main() 63 { 64 int T; 65 cin >> T; 66 while(T --) 67 { 68 read(); 69 int rnt = solve(); 70 print(rnt); 71 } 72 return 0; 73 }
原文:https://www.cnblogs.com/Asurudo/p/10023393.html