|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
rt.洛谷没人回答我,那我只好上这问了。
题目链接:https://www.luogu.com.cn/problem/P1746
问题:https://www.luogu.com.cn/discuss/689287
code:
- #include <cstdio>
- #include <cstring>
- #include <queue>
- using namespace std;
- typedef struct
- {
- int x;
- int y;
- int step;
- }point;
- int main()
- {
-
- int n,mp[1145][1145],x1,y1,x2,y2,ch,bx[]={-1,0,0,1},by[]={0,1,-1,0};
- bool road[1145][1145]={};
- scanf("%d",&n);
- getchar();
- for(int i=0;i<=n;i++)
- {
- for(int j=0;j<=n;j++)
- {
- mp[i][j]=-1;
- }
- }
- for(int i=1;i<=n;i++)
- {
-
- for(int j=1;j<=n;j++)
- {
- ch=getchar();
- if(ch=='0')road[i][j]=true;//okay.
- //putchar(ch);
- }
- getchar();
- //putchar('\n');
- }
- scanf("%d%d%d%d",&x1,&y1,&x2,&y2);
- queue<point> q;
- q.push((point){x1,y1,0});
- while(!(q.empty()))
- {
- for(int i=0;i<4;i++)
- {
- if(road[q.front().x+bx[i]][q.front().y+by[i]] and mp[q.front().x+bx[i]][q.front().y+by[i]]==-1)
- {
- //putchar('-');
- mp[q.front().x+bx[i]][q.front().y+by[i]]=q.front().step+1;
- //printf("++%d %d++",q.front().x,q.front().y);
- q.push((point){q.front().x+bx[i],q.front().y+by[i],q.front().step+1});
- }
- }
- q.pop();
- }
- printf("%d\n",mp[x2][y2]);
-
- }
复制代码
本帖最后由 柿子饼同学 于 2023-9-23 11:20 编辑
你代码风格有点...
我自己写了以下, 过了, 你自己看下呢
写代码不要写特别繁琐 , 不然看不出来的
- #include <bits/stdc++.h>
- using namespace std;
- const int N = 1314;
- const int dx[] = {0, 1, 0, -1};
- const int dy[] = {1, 0, -1, 0};
- struct Step{
- int x, y, step;
- };
- bitset<N> mp[N]; // 地图
- bitset<N> vis[N];
- int n, X1, X2, Y1, Y2;
- char ch;
- queue<Step> q;
- bool check(int x, int y){
- return (x > 0 && x <= n && y > 0 && y <= n && !mp[x][y] && !vis[x][y]);
- }
- int bfs(){
- q.push({X1, Y1, 0});
- vis[X1][Y1] = 1;
- while(!q.empty()){
- auto cur = q.front();
- q.pop();
- if(cur.x == X2 && cur.y == Y2){
- return cur.step;
- }
- for(int i = 0; i < 4; i++){
- auto px = cur.x + dx[i];
- auto py = cur.y + dy[i];
- if(check(px, py)){
- vis[px][py] = 1;
- q.push({px, py, cur.step + 1});
- }
- }
- }
- return -1;
- }
- int main(){
- ios::sync_with_stdio(0);
- cin.tie(0);
- cin >> n;
- for(int i = 1; i <= n; i++){
- for(int j = 1; j <= n; j++){
- cin >> ch;
- if(ch == '1') mp[i][j] = 1;
- }
- }
- cin >> X1 >> Y1 >> X2 >> Y2;
- cout << bfs();
- return 0;
- }
复制代码
|
|