1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
|
#include <iostream>
#include <fstream>
const int Max = 1001;
using namespace std;
void readPath(int path[Max][Max], int &lin, int &col);
void borderPath(int path[Max][Max], int lin, int col);
int checkPath(int path[Max][Max], int x, int y);
int main(int argc, char* argv[])
{
int path[Max][Max];
int lin = 0; // initializing number of lines
int col = 0; // initializing number of columns
int k = 0, i = 1, j = 1; // k - the length of the path; i - the current line; j - the current column.
readPath(path,lin,col);
borderPath(path,lin,col);
do
{
if (checkPath(path,i+1,j+1) == 1)
{
i++; j++; k++; path[i][j] = -1;
}
else
{
if (checkPath(path,i+1,j) == 1)
{
i++; k++; path[i][j] = -1;
}
else
{
if (checkPath(path,i+1,j-1) == 1)
{
i++; j--; k++; path[i][j] = -1;
}
else
{
if (checkPath(path,i,j+1) == 1)
{
j++; k++; path[i][j] = -1;
}
else
{
if (checkPath(path,i,j-1) == 1)
{
j--; k++; path[i][j] = -1;
}
else
{
if (checkPath(path,i-1,j+1) == 1)
{
i--; j++; k++; path[i][j] = -1;
}
else
{
if (checkPath(path,i-1,j) == 1)
{
i--; k++; path[i][j] = -1;
}
else
{
if (checkPath(path,i-1,j-1) == 1)
{
i--; j--; k++; path[i][j] = -1;
}
}
}
}
}
}
}
}
}while(i != lin && j != col);
cout << "The shortest path found has the length: " << k << ".\n";
return 0;
}
void readPath(int path[Max][Max], int &lin, int &col)
{
ifstream _inFILE("path.txt");
_inFILE >> lin >> col;
for (int i = 1; i <= lin; i++)
{
for (int j = 1; j <= col; j++)
{
_inFILE >> path[i][j];
}
}
}
void borderPath(int path[Max][Max], int lin, int col)
{
for (int i = 0; i <= lin+1; i++)
{
path[i][0] = path[i][col+1] = 1;
}
for (int j = 0; j <= col+1; j++)
{
path[0][j] = path[lin+1][j] = 1;
}
}
int checkPath(int path[Max][Max], int x, int y)
{
if (path[x][y] == 0)
return 1;
else
return 0;
}
|