3 solutions

  • 0
    @ 2023-10-22 23:24:41
    #include<iostream>
    using namespace std;
    #define N 20
    struct point {
    	int x;
    	int y;
    };
    bool vis[N][N];
    point path[N*N];
    int dx[4]={2,1,-1,-2};
    int dy[4]={1,2,2,1};
    int cnt;
    void dfs(int x,int y,int step){
    	if(x==4&&y==8){
    		cnt++;
    		cout<<cnt<<":";
    		for(int i=0;i<step;i++)cout<<path[i].x<<","<<path[i].y<<"->";
    		cout<<"4,8"<<endl;
    		return ;
    	}
    	for(int i=0;i<4;i++){
    		int tx=x+dx[i];
    		int ty=y+dy[i];
    		if(tx<0||ty<0||tx>=5||ty>=9)continue;
    		step++;
    		path[step].x=tx;
    		path[step].y=ty;
    		vis[tx][ty]=true;
    		dfs(tx,ty,step);
    		vis[tx][ty]=false;
    		step--;
    	}
    }
    int main(){
    	path[0].x=0;
    	path[0].y=0;
    	vis[0][0]=true;
    	dfs(0,0,0);
    	return 0;
    }
    
    • 0
      @ 2022-4-10 19:35:57
      #include<iostream>
      using namespace std;
      int n,m,sum;
      struct data{
      	int p,q;
      }a[110];
      int dx[4]={2,1,-1,-2};
      int dy[4]={1,2,2,1};
      int g[110][110];
      void dfs(int x,int y,int u)
      {
      	if(x==4&&y==8)
      	{
      		a[u].p=x;
      		a[u].q=y;
      		sum++;
      		cout<<sum<<":"<<a[1].p<<","<<a[1].q;
      		for(int i=2;i<=u;i++)
      			cout<<"->"<<a[i].p<<","<<a[i].q;
      		cout<<endl;
      		return ;
      	}
      	a[u].p=x;
      	a[u].q=y;
      	g[x][y]=1;
      	for(int i=0;i<4;i++)
      	{
      		int xx=x+dx[i],yy=y+dy[i];
      		if(xx>=0&&yy>=0&&xx<=4&&yy<=8&&!g[xx][yy])
      		{
      			dfs(xx,yy,u+1);
      			g[x][y]=0;
      		}
      	}
      } 
      int main(){
      	dfs(0,0,1);
      	return 0;
      }
      /*
      bfs是一层层开始扫荡
      dfs是一条道走到黑
      求方案数,走完了一条返回接着走 
      dfs的参数一定要确定好 
      */
      
      • 0
        @ 2022-2-16 13:12:04
        #include<bits/stdc++.h>
        using namespace std;
        int n,m,cnt=1;
        int a[2][10];
        void dfs(int x,int y,int len,int a[][10]){
        	a[0][len]=x;
        	a[1][len]=y;
        	if(x>n||y>m||x<0||y<0)
        	return;
        	else if(x==n&&y==m){
        		cout<<cnt<<":";
        		cnt++;
        		for(int i=0;i<=len;i++){
        			if(i==len)
        			printf("%d,%d\n",a[0][i],a[1][i]);
        			else
        			printf("%d,%d->",a[0][i],a[1][i]);
        		}
        		return;
        	}
        	dfs(x+2,y+1,len+1,a);
        	dfs(x+1,y+2,len+1,a);
        	dfs(x-1,y+2,len+1,a);
        	dfs(x-2,y+1,len+1,a);
        }
        int main()
        {
        	//cin>>n>>m;
        	n=4,m=8;
        	dfs(0,0,0,a);
        	return 0;
        }
        
        • 1

        Information

        ID
        699
        Time
        1000ms
        Memory
        16MiB
        Difficulty
        5
        Tags
        # Submissions
        96
        Accepted
        36
        Uploaded By