2 solutions

  • 1
    @ 2022-4-28 11:24:47

    记忆化+dfs

    #include<bits/stdc++.h>
    using namespace std;
    typedef long long ll;
    const int N = 1e3 + 7;
    int n,m;
    int s1,s2,e1,e2;
    int ma[N][N],dp[N][N],vis[N][N];
    int dx[]={0,0,1,-1},dy[]={1,-1,0,0};
    void dfs(int x,int y,int sum,int op){
    	if(sum>=dp[x][y])return ;
    	vis[x][y]=1;
    	dp[x][y]=min(dp[x][y],sum);
    	for(int i=0;i<4;i++){
    		int xx=x+dx[i];
    		int yy=y+dy[i];
    		if(xx>=1&&xx<=n&&yy>=1&&yy<=m&&ma[xx][yy]==0&&vis[xx][yy]==0){
    			if(i!=op)dfs(xx,yy,sum+1,i);
    			else dfs(xx,yy,sum,i);
    		}
    	}
    	vis[x][y]=0;
    }
    int main() {
    	memset(dp,0x3f,sizeof dp);
    	cin>>n>>m;
    	for(int i=1;i<=n;i++)
    		for(int j=1;j<=m;j++)
    			cin>>ma[i][j];
    	cin>>s1>>s2>>e1>>e2;
    	dp[s1][s2]=0;
    	if(s1+1<=n&&ma[s1+1][s2]==0) dfs(s1+1,s2,0,2);
    	if(s1-1>=1&&ma[s1-1][s2]==0) dfs(s1-1,s2,0,3);
    	if(s2+1<=m&&ma[s1][s2+1]==0) dfs(s1,s2+1,0,0);
    	if(s2-1>=1&&ma[s1][s2-1]==0) dfs(s1,s2-1,0,1);
    	cout<<dp[e1][e2]<<endl;
    	return 0;
    }
    
    • 0
      @ 2022-1-21 20:45:02
      #include<bits/stdc++.h>
      using namespace std;
      const int dx[]={0,1,0,-1};
      const int dy[]={1,0,-1,0};
      struct node{
          int x,y,turn;
      }s,t,p;
      queue<node> q;
      int n,m,c[1005][1005];
      bool v[1005][1005];
      int main()
      {
       
          scanf("%d %d",&n,&m);
          for(int i=1;i<=n;i++)
          for(int j=1;j<=m;j++)
          scanf("%d",&c[i][j]);
          scanf("%d%d%d%d",&s.x,&s.y,&t.x,&t.y);
          q.push(s);
          memset(v,0,sizeof(v));
          q.front().turn=0;
          while(!q.empty())
          {
              for(int i=0;i<4;i++)
              {
                  p.x=q.front().x+dx[i];
                  p.y=q.front().y+dy[i];
                  while(p.x>0&&p.x<=n&&p.y>0&&p.y<=m&&!c[p.x][p.y])
                  {
                      if(!v[p.x][p.y])
                      {
                          if(p.x==t.x&&p.y==t.y)
                          {
                              printf("%d\n",q.front().turn);
                              return 0;
                          }
                          v[p.x][p.y]=1;
                          p.turn=q.front().turn+1;
                          q.push(p);
                      }
                      p.x+=dx[i];
                      p.y+=dy[i];
                  }
              }
              q.pop();
          }
      }
      
      • 1

      Information

      ID
      781
      Time
      1000ms
      Memory
      128MiB
      Difficulty
      7
      Tags
      # Submissions
      53
      Accepted
      13
      Uploaded By