[HDU] 1372 Knight Moves 每步走马步(日字)的广搜
题目链接:
http://acm.hdu.edu.cn/showproblem.php?pid=1372
方法:建模后的广搜是最基本的单位权值边单源最短路径。所以不需要使用优先队列,直接用普通队列来维护广搜即可。
感想:基础题。
代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include <iostream> #include <queue> using namespace std; bool visited[9][9]; char chessboard [9][9]; int derection[8][2]; struct cell { int x,y; int currentSteps; }; bool canGo(int x,int y) { if(x<1||x>8 || y<1|| y>8) return false; return !visited[x][y]; } int search(int startX, int startY,int endX, int endY) { cell* cur = (cell*)malloc(sizeof(cell)); cur->x = startX; cur->y= startY; cur->currentSteps =0; visited[cur->x][cur->y] = true; queue<cell*> Q; Q.push(cur); int result=-1; while(!Q.empty()) { cur = Q.front(); Q.pop(); if(cur->x == endX && cur->y == endY) { result = cur->currentSteps; break; } else { for(int i = 0;i<8;i++) { int x = cur->x+derection[i][0]; int y = cur->y+derection[i][1]; if(canGo(x,y)) { cell* newCell = (cell*) malloc(sizeof(cell)); visited[x][y] = true; newCell->x=x; newCell->y=y; newCell->currentSteps = cur->currentSteps+1; Q.push(newCell); } } } delete[] cur; } while(!Q.empty()) { delete[] Q.front(); Q.pop(); } return result; } void main() { derection[0][0] = -2;derection[0][1] = 1; derection[1][0] = -1;derection[1][1] = 2; derection[2][0] = 1;derection[2][1] = 2; derection[3][0] = 2;derection[3][1] = 1; derection[4][0] = 2;derection[4][1] =-1; derection[5][0] = 1;derection[5][1] =-2; derection[6][0] = -1;derection[6][1] =-2; derection[7][0] = -2;derection[7][1] =-1; int s=0,t=0; char* start=new char[2]; char* end=new char[2]; while( scanf("%s %s",start,end)!= EOF ) { int startX=start[1]-48; int startY=start[0]-96; int endX=end[1]-48; int endY=end[0]-96; for(int i =1;i<=8;i++) for(int j =1;j<=8;j++) visited[i][j]=false; int result = search(startX,startY,endX,endY); printf("To get from %s to %s takes %d knight moves.\n",start,end,result); } }