1. 程式人生 > >洛谷P1443 馬的遍歷

洛谷P1443 馬的遍歷

輸出 ace names 兩個 循環 std 方向 push 隊列

https://www.luogu.org/problemnew/show/P1443

很經典的搜索題了,蒟蒻用廣搜打的

不說了,上代碼!

#include<bits/stdc++.h>
using namespace std;
struct xy {//定義結構體
    int x,y;//x,y兩個方向
} node,Top;
int dx[8]={2,-2,2,-2,-1,1,-1,1};
int dy[8]={1,1,-1,-1,2,2,-2,-2};//馬走的八個方向
int a[401][401];
bool b[401][401];
int n,m;
void bfs(int
x,int y,int step) {//廣搜函數 a[x][y]=step; b[x][y]=false; queue<xy>q;//建立一個隊列 node.x=x; node.y=y; q.push(node);//入隊 while (!q.empty()){//如果隊列不為空就循環 Top=q.front();//取隊首元素 q.pop();//出隊 for (int i=0;i<8;i++){ int newx=Top.x+dx[i];
int newy=Top.y+dy[i];//往八個方向遍歷 if (newx<1||newx>n||newy<1||newy>m) continue;//判斷是否越界 if (b[newx][newy]){//如果該點沒有標記過 node.x=newx; node.y=newy;//更新 q.push(node);//入隊 b[newx][newy]=false;//標記 a[newx][newy]=a[Top.x][Top.y]+1
;//步數+1 } } } } int main() { memset(b,true,sizeof(b)); memset(a,-1,sizeof(a));//數組初始化 int x,y; cin>>n>>m>>x>>y;//輸入 bfs(x,y,0);//廣搜 for (int i=1; i<=n; i++) { for (int j=1; j<=m; j++) printf("%-5d", a[i][j]);//輸出五位常寬 cout<<endl;//換行 } return 0; }

洛谷P1443 馬的遍歷