C++ 矩阵中的最短路径
有一个30x30矩阵,包含0,1,2个随机元素。我需要找到从矩阵顶部到底部的最短路径。我只能在1分钟内搬家。我不知道这有什么问题 守则:C++ 矩阵中的最短路径,c++,matrix,C++,Matrix,有一个30x30矩阵,包含0,1,2个随机元素。我需要找到从矩阵顶部到底部的最短路径。我只能在1分钟内搬家。我不知道这有什么问题 守则: #include <iostream> #include <ctime> #include <cstdlib> #define max 30 using namespace std; int matrix[max][max]; int smatrix[max][max]; ///all elements are 0
#include <iostream>
#include <ctime>
#include <cstdlib>
#define max 30
using namespace std;
int matrix[max][max];
int smatrix[max][max]; ///all elements are 0
int lenght=0; ///út hossza
void showMtx()
{
for(int i=0; i<max; i++)
{
cout<<i+1<<".\t";
for(int j=0; j<max; j++)
{
//if(matrix[i][j]==1)cout<<"k ";
//else cout<<" ";
cout<<matrix[i][j]<<" ";
}
cout<<"\n";
}
}
void path()
{
for(int i=0; i<max; i++)
{
for(int j=0; j<max; j++)
{
if(matrix[i+1][j+1]==1 && smatrix[i+1][j+1]!=1) ///diagonally down
{
smatrix[i+1][j+1]=1; ///indicates that the i and j was here
lenght++; ///step counter
cout<<"->("<<i+1<<","<<j+1<<")";
}
else if(matrix[i][j+1]==1 && smatrix[i][j+1]!=1) ///right
{
smatrix[i][j+1]=1;
lenght++;
cout<<"->("<<i<<","<<j+1<<")";
}
else if(matrix[i+1][j]==1 && smatrix[i+1][j]!=1) /// down
{
matrix[i+1][j-1]=1;
lenght++;
cout<<"->("<<i+1<<","<<j<<")";
}
else if(matrix[i+1][j-1] && smatrix[i+1][j-1]!=1) ///diagonally down up
{
smatrix[i+1][j-1]=1;
lenght++;
cout<<"->("<<i+1<<","<<j-1<<")";
}
else if(matrix[i][j-1]==1 && smatrix[i][j-1]!=1) ///left
{
lenght++;
smatrix[i][j-1]=1;
cout<<"->("<<i<<","<<j-1<<")";
}
else if(matrix[i-1][j]==1 && smatrix[i-1][j]!=1) ///up
{
lenght++;
smatrix[i-1][j]=1;
cout<<"->("<<i-1<<","<<j<<")";
}
else if(matrix[i-1][j-1]==1 && smatrix[i-1][j-1]!=1) /// diagonally down
{
lenght++;
smatrix[i-1][j-1]=1;
cout<<"->("<<i-1<<","<<j-1<<")";
}
else
{
}
if(i==30)break;
}
}
}
void shortestPath()
{
int i=0,j;
for(j=0; j<max; j++) ///find the first 1
{
if(matrix[i][j]==1)
{
path();
break;
}
}
cout<<"\nlepesek szama: "<<lenght<<endl;
}
int main()
{
srand(time(NULL));
for(int i=0; i<max; i++)
{
for(int j=0; j<max; j++)
{
matrix[i][j]=rand()%3;
smatrix[i][j]=0;
}
}
showMtx();
cout<<endl;
shortestPath();
return 0;
}
#包括
#包括
#包括
#定义最大值30
使用名称空间std;
整数矩阵[max][max];
int smatrix[max][max]///所有元素都是0
整数长度=0///út hossza
void showMtx()
{
对于(i=0;i当i=0
和i=max-1
时,i-1
和i=max-1
的值是多少?i=0;i是什么值?i-1
和i+1
)?处理转角情况!!哦,我忘了这一点。添加了加号条件,但仍然不能正常工作。需要470-500步我应该使用while loop而不是for?