c++ 算法 栅格中两点之间连线
屏幕划线,通过平面坐标系实现,基本组成是一个一个的点,起点为A,终点为B
本文的算法,可以实现平面栅格中,指定的A,B两点之间进行连线(代码中仅打印了两点间需要画出的坐标点)
#include <iostream> #include <algorithm> using namespace std; void paint(int,int); void paint(int i,int j){ //画出点位 cout<<i<<",,"<<j<<endl; } int main () { int A[] = {7,2};//起点 int B[]={7,2};//终点 int Ax=-1,Ay=-1,Bx=-1,By=-1; Ax=A[0]; Ay=A[1]; Bx=B[0]; By=B[1]; int width,height,left=-1,times=-1,shu=-1; width=abs(Ax-Bx)+1; height=abs(Ay-By)+1; if(width>height){ shu=0; times=width/height; cout<<"0times"<<times<<endl; left=width%height; cout<<"0left"<<left<<endl; }else if(width<height){ shu=1; times=height/width; cout<<"1times"<<times<<endl; left=height%width; cout<<"1left"<<left<<endl; }else{ shu=2; } if(Ax>Bx){ if(Ay>By){ if(shu==2){ for(int i=0;i<height;i++){ paint(Bx+i,By+i); } }else if(shu==1){ for(int i=0;i<width;i++){ if(left>0){ for(int j=0;j<times+1;j++){ paint(Bx,By); By+=1; } Bx+=1; }else{ for(int j=0;j<times;j++){ paint(Bx,By); By+=1; } Bx+=1; } left-=1; } }else{ for(int i=0;i<height;i++){ if(left>0){ for(int i=0;i<times+1;i++){ paint(Bx,By); Bx+=1; } By+=1; }else{ for(int j=0;j<times;j++){ paint(Bx,By); Bx+=1; } By+=1; } left-=1; } } }else if(Ay<By){ if(shu==2){ for(int i=0;i<height;i++){ paint(Bx+i,By-i); } }else if(shu==1){ for(int i=0;i<width;i++){ if(left>0){ for(int j=0;j<times+1;j++){ paint(Bx,By); By-=1; } Bx+=1; }else{ for(int j=0;j<times;j++){ paint(Bx,By); cout<<"dede"<<endl; By-=1; } Bx+=1; } left-=1; } }else{ for(int i=0;i<height;i++){ if(left>0){ for(int i=0;i<times+1;i++){ paint(Bx,By); Bx+=1; } By-=1; }else{ for(int j=0;j<times;j++){ paint(Bx,By); Bx+=1; } By-=1; } left-=1; } } }else{ for(int i=0;i<width;i++){ paint(Bx+i,By); } } }else if(Ax<Bx){ if(Ay>By){ if(shu==2){ for(int i=0;i<height;i++){ paint(Ax+i,Ay-i); } }else if(shu==1){ for(int i=0;i<width;i++){ if(left>0){ for(int j=0;j<times+1;j++){ paint(Ax,Ay); Ay-=1; } Ax+=1; }else{ for(int j=0;j<times;j++){ paint(Ax,Ay); Ay-=1; } Ax+=1; } left-=1; } }else{ for(int i=0;i<height;i++){ if(left>0){ for(int i=0;i<times+1;i++){ paint(Ax,Ay); Ax+=1; } Ay-=1; }else{ for(int j=0;j<times;j++){ paint(Ax,Ay); Ax+=1; } Ay-=1; } left-=1; } } }else if(Ay<By){ if(shu==2){ for(int i=0;i<height;i++){ paint(Ax+i,Ay+i); } }else if(shu==1){ for(int i=0;i<width;i++){ if(left>0){ for(int j=0;j<times+1;j++){ paint(Ax,Ay); Ay+=1; } Ax+=1; }else{ for(int k=0;k<times;k++){ paint(Ax,Ay); Ay+=1; } Ax+=1; } left-=1; } }else{ for(int i=0;i<height;i++){ if(left>0){ for(int i=0;i<times+1;i++){ paint(Ax,Ay); Ax+=1; } Ay+=1; }else{ for(int j=0;j<times;j++){ paint(Ax,Ay); Ax+=1; } Ay+=1; } left-=1; } } }else{ for(int i=0;i<width;i++){ paint(Ax+i,Ay); } } }else{ if(Ay>By){ for(int i=0;i<height;i++){ paint(Bx,By+i); } }else if(Ay<By){ for(int i=0;i<height;i++){ paint(Ax,Ay+i); } }else{ for(int i=0;i<width;i++){ paint(Ax,Ay); } } } return 0; }