标签:style blog io ar color os sp for on
1 #include <iostream> 2 #include <fstream> 3 #include <cstring> 4 #include "unistd.h" 5 #include<sys/time.h> 6 #include<sys/types.h> 7 using namespace std; 8 #define MAX_ROW 20 9 #define MAX_COL 20 10 #define MAX_STACK_SIZE 400 11 #define EXIT_ROW 11 12 #define EXIT_COL 16 13 char map[MAX_ROW][MAX_COL]; 14 char mark[MAX_ROW][MAX_COL]; 15 16 int row ,col; 17 void loadMap(int* row,int *col) { 18 ifstream fin("map.txt"); 19 fin>>*row>>*col; 20 *row += 2; 21 *col+=2; 22 for(int i=0; i<*row; i++) { 23 for(int j=0; j<*col; j++) { 24 fin>>map[i][j]; 25 mark[i][j] = map[i][j]; 26 } 27 } 28 } 29 30 void printMap() { 31 for(int i=0; i<row; i++) { 32 for(int j=0; j<col; j++) { 33 cout<<mark[i][j]<<" "; 34 } 35 cout<<endl; 36 } 37 } 38 struct offsets { 39 short int vert; 40 short int horiz; 41 }; 42 offsets move[8]= {-1,0, -1,1, 0,1, 1,1, 1,0, 1,-1, 0,-1, -1,-1}; 43 44 struct element { 45 short int row; 46 short int col; 47 short int dir; 48 }; 49 element stack[MAX_STACK_SIZE]; 50 int top = -1; 51 52 element delete_stack(int *t) { 53 return stack[(*t)--]; 54 } 55 void add(int *t,element ele) { 56 stack[++*t] = ele; 57 } 58 void path() { 59 60 int i,row,col,next_row,next_col,dir; 61 bool found=false; 62 element position; 63 mark[1][0]=‘$‘; 64 top = 0; 65 stack[0].row = 1; 66 stack[0].col = 0; 67 stack[0].dir = 0; 68 while(top>-1&&!found) { 69 position = delete_stack(&top); 70 mark[position.row][position.col]=‘1‘; 71 row = position.row; 72 col = position.col; 73 dir = position.dir; 74 printMap(); 75 usleep(500000); 76 while(dir<8&&!found) { 77 next_row = row + move[dir].vert; 78 next_col = col + move[dir].horiz; 79 if(next_row==EXIT_ROW&&next_col ==EXIT_COL) { 80 found = true; 81 } else if(map[next_row][next_col]==‘0‘&&mark[next_row][next_col]==‘0‘) { 82 mark[next_row][next_col]=‘$‘; 83 position.row = row; 84 position.col = col; 85 position.dir = ++dir; 86 add(&top,position); 87 printMap(); 88 usleep(500000); 89 row = next_row; 90 col = next_col; 91 dir = 0; 92 } else ++dir; 93 } 94 95 } 96 if(found) { 97 cout<<"you win!"<<endl; 98 } else { 99 cout<<"do not have a path!"<<endl; 100 } 101 } 102 int main() { 103 loadMap(&row,&col); 104 printMap(); 105 path(); 106 return 0; 107 }
标签:style blog io ar color os sp for on
原文地址:http://www.cnblogs.com/daipeiwu/p/4161874.html