解题思路:
注意事项:
参考代码:
暴力bfs:
#include <iostream> #include <stdio.h> #include <queue> #include <string.h> using namespace std; typedef struct { int x, y; int step; }Point; int m ,n; char map[150][150]; int mark[150][150]; Point sta, e, cur, ne; int dir[8][2] = {{-1,-2},{1,-2},{-1,2},{1,2},{-2,-1},{2,-1},{-2,1},{2,1}};//8个方向 queue<Point>q; int bfs(); int main() { int i, j, step; scanf("%d%d",&m,&n); getchar();//此处getchar()不可省,否则坑爹 for(i=0; i<n; i++) { scanf("%s",map[i]); for(j=0; j<m; j++) { if(map[i][j] == 'K') { sta.x = i; sta.y = j; } if(map[i][j] == 'H') { e.x = i; e.y = j; } } } step = bfs(); printf("%d\n",step); return 0; } int bfs() { int i; while(!q.empty())//初始化队列 q.pop(); sta.step = 0; mark[sta.x][sta.y] = 1; q.push(sta); while(!q.empty()) { cur = q.front(); q.pop(); if(cur.x == e.x && cur.y == e.y) return cur.step; for(i=0; i<8; i++) { ne.x = cur.x + dir[i][0]; ne.y = cur.y + dir[i][1]; ne.step = cur.step + 1; if(ne.x >= 0 && ne.x < n && ne.y >= 0 && ne.y < m && map[ne.x][ne.y] != '*' && mark[ne.x][ne.y] == 0) { q.push(ne); mark[ne.x][ne.y] = 1; } } } }
0.0分
15 人评分
C语言程序设计教程(第三版)课后习题5.4 (C++代码)按照惯例的只有一行核心代码浏览:952 |
点我有惊喜!你懂得!浏览:1322 |
川哥的吩咐 (C语言代码)浏览:871 |
字符串输入输出函数 (Java代码)浏览:1435 |
C语言程序设计教程(第三版)课后习题1.5 (C语言代码)浏览:633 |
C语言程序设计教程(第三版)课后习题1.6 (C语言代码)浏览:653 |
【金明的预算方案】 (C++代码)浏览:934 |
【绝对值排序】 (C语言代码)浏览:820 |
C语言考试练习题_一元二次方程 (C语言代码)浏览:574 |
C语言程序设计教程(第三版)课后习题1.6 (C语言代码)浏览:466 |