解题思路:跟着BFS的模板走就可以了,唯一要注意的是要用输出字典序,把方向的数组dir按照的一定的顺序排列即可
注意事项:
参考代码:
#include<bits/stdc++.h> using namespace std; int n, m; char mp[510][510]; int vis[510][510]; int dir[4][2] = {1, 0, 0, -1, 0, 1, -1, 0}; string l = "DLRU"; struct node{ int x, y, step; string s; node(){} node(int xx, int yy, int st, string ss){ x = xx; y = yy; step = st; s =ss; } }; int in(int x, int y){ return x >= 1 && x <= n && y >= 1 && y <= m; } void bfs(node x){ queue<node> q; q.push(x); vis[1][1] = 1; while(!q.empty()){ int xx, yy; node now; now = q.front(); q.pop(); if(now.x == n && now.y == m){ cout<<now.step<<endl<<now.s; return; } for(int i = 0; i < 4; i++){ xx = now.x + dir[i][0]; yy = now.y + dir[i][1]; if(in(xx, yy) && !vis[xx][yy] && mp[xx][yy] == '0'){ vis[xx][yy] = 1; q.push(node(xx, yy, now.step + 1, now.s + l[i])); } } } } int main(){ cin>>n>>m; for(int i = 1; i <= n; i++){ for(int j = 1; j <= m; j++){ cin>>mp[i][j]; } } node x = node(1 ,1, 0, ""); bfs(x); return 0; }
0.0分
1 人评分
震宇大神的杀毒软件 (C++代码)浏览:1103 |
2006年春浙江省计算机等级考试二级C 编程题(1) (C语言代码)浏览:799 |
C语言训练-计算一个整数N的阶乘 (C语言代码)浏览:926 |
C语言程序设计教程(第三版)课后习题7.1 (C语言代码)浏览:724 |
剪刀石头布 (C语言代码)浏览:1744 |
哥德巴赫曾猜测 (C语言代码)浏览:2313 |
C语言程序设计教程(第三版)课后习题1.6 (C语言代码)浏览:536 |
C语言程序设计教程(第三版)课后习题1.5 (C语言代码)浏览:520 |
1054题解浏览:460 |
C语言程序设计教程(第三版)课后习题10.2 (C语言代码)浏览:678 |