#include <iostream> #include <queue> using namespace std; #define MAX_COL 100 #define MAX_ROW 100 #define MAX_DIR 4 #define PATH '.' #define BLOCK '*' #define SHORT_WAY '@' #define STNOE '&' struct Point { int row, col; }; void Find_Way(char maze[MAX_ROW][MAX_COL], const Point & start_pos, Point & end_pos); int main(void) { char maze[MAX_ROW][MAX_COL]; int N, row, col; cout << "input the sample run times:\n"; cin >> N; while ( N-- ) { cout << "input the map row and col\nlike this:5 9\n"; cin >> row >> col; cout << "input the map(block: *, path: . way: @):\n"; for (int i = 0; i < row; i++) for (int j = 0; j < col; j++) cin >> maze[ i ][ j ]; Point start_pos, end_pos; cout << "input the start position and end position\nlike this:1 1 3 4\n"; cin >> start_pos.row >> start_pos.col >> end_pos.row >> end_pos.col; start_pos.row--, start_pos.col--, end_pos.row--, end_pos.col--; Find_Way(maze, start_pos, end_pos); } return 0; } void Find_Way(char maze[MAX_ROW][MAX_COL], const Point & start_pos, Point & end_pos) { if (start_pos.row == end_pos.row && start_pos.col == end_pos.col) return ; unsigned int record[MAX_ROW][MAX_COL] = { 0 }; short record_dir[MAX_ROW][MAX_COL] = { 0 }; Point cur_pos = {start_pos.row, start_pos.col}; queue<Point> que; que.push(cur_pos); record[cur_pos.row][cur_pos.col] = 1; while (que.size()) { cur_pos = que.front(); que.pop(); short row, col;//行,列 for (int i = 0; i < MAX_DIR; ++i) { switch ( i ) { case 0://上 row = -1, col = 0; break; case 1://右 row = 0, col = 1; break; case 2://下 row = 1, col = 0; break; case 3://左 row = 0, col = -1; }//switch int base = record[cur_pos.row][cur_pos.col]; row += cur_pos.row, col += cur_pos.col; short weigth = 1; if (maze[row][col] == STNOE) weigth += 50; if ((record[row][col] > base + weigth || !record[row][col]) && maze[row][col] != BLOCK && row >= 0 && row < MAX_ROW && col >= 0 && col < MAX_COL ) { record[row][col] = (base + weigth); record_dir[row][col] = i; Point t = {row, col}; que.push(t); }//if }//for //if (row == end_pos.row && col == end_pos.col) // break; }//while for (int i = 0; i < 12; ++i) { cout << '\n'; for (int j = 0; j < 10; ++j) cout << record[i][j] << ' '; } cout << '\n' << endl; for (i = 0; i < 12; ++i) { cout << '\n'; for (int j = 0; j < 10; ++j) cout << record_dir[i][j] << ' '; } cout << '\n' << endl; if (record[end_pos.row][end_pos.col]) { Point t = {end_pos.row, end_pos.col};//&& reach_end_pos while ((start_pos.row != t.row || start_pos.col != t.col)) { end_pos.row = t.row, end_pos.col = t.col; switch (record_dir[t.row][t.col]) { case 0: t.row += 1; maze[t.row][t.col] = 'R'; break; case 1: t.col -= 1; maze[t.row][t.col] = 'R'; break; case 2: t.row -= 1; maze[t.row][t.col] = 'R'; break; case 3: t.col += 1; maze[t.row][t.col] = 'R'; }//switch }//while }//if cout << "next row:" << end_pos.row << "next col:" << end_pos.col << endl; for (i = 0; i < 12; ++i) { cout << '\n'; for (int j = 0; j < 10; ++j) cout << maze[i][j]; } }