NYOJ 58 最少步數 【BFS】

來源:互聯網
上載者:User

標籤:bfs

題意:不解釋。

策略:如題;

這道題可以用深搜也可以用廣搜,我以前寫的是用的深搜,最近在學廣搜,就拿這道題來練練手。

代碼:

#include<stdio.h>#include<string.h>#include<queue>using std::queue;bool vis[20][20];const int dir[4][2] = {1, 0, -1, 0, 0, 1, 0, -1};//方向int map[9][9] = {1,1,1,1,1,1,1,1,1, 1,0,0,1,0,0,1,0,1, 1,0,0,1,1,0,0,0,1, 1,0,1,0,1,1,0,1,1, 1,0,0,0,0,1,0,0,1, 1,1,0,1,0,1,0,0,1, 1,1,0,1,0,1,0,0,1, 1,1,0,1,0,0,0,0,1, 1,1,1,1,1,1,1,1,1,};struct Node{int pos[2];//pos[0] = x, pos[1] = yint step;};Node st, en;bool match(Node a, Node b)  //判斷是不是到達終點{return (a.pos[0] == b.pos[0]&&a.pos[1] == b.pos[1]);}int bfs(){queue<Node> q;int i, j;memset(vis, 0, sizeof(vis)); q.push(st);vis[st.pos[0]][st.pos[1]] = 1;int ans = 0x3f3f3f3f;  //初始化while(!q.empty()){Node u = q.front();if(match(u, en)){    //wa了一次是因為沒有判斷終點是不是起點ans = u.step;break;}for(i = 0; i < 4; i ++){Node v;v.pos[0] = u.pos[0]+dir[i][0];v.pos[1] = u.pos[1]+dir[i][1];v.step = u.step+1;if(match(v, en)){if(v.step < ans)ans = v.step;}else if(!vis[v.pos[0]][v.pos[1]]&&!map[v.pos[0]][v.pos[1]]){q.push(v);vis[v.pos[0]][v.pos[1]] = 1;}}q.pop();}return ans;}int main(){int t;scanf("%d", &t);while(t --){scanf("%d%d%d%d", &st.pos[0], &st.pos[1], &en.pos[0], &en.pos[1]);st.step = 0;printf("%d\n", bfs());}return 0;}


題目連結:http://acm.nyist.net/JudgeOnline/problem.php?pid=58


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.