广搜
# include <iostream>
# include <string.h>
# include <queue>
# include <algorithm>
using namespace std;
int mp[ 110 ] [ 110 ] ;
int vis[ 110 ] [ 110 ] ;
int f[ 4 ] [ 2 ] = { 1 , 0 , 0 , 1 , - 1 , 0 , 0 , - 1 } ;
int eny, enx, stx, sty;
struct node {
int x;
int y;
int step;
} u, v;
int n, m;
bool check ( int x, int y) {
if ( x>= 1 && x<= n&& y>= 1 && y<= m) return true ;
else return false ;
}
void bfs ( ) {
queue< node> q;
memset ( vis, 0 , sizeof ( vis) ) ;
u. x= stx;
u. y= sty;
u. step= 0 ;
vis[ stx] [ sty] = 1 ;
q. push ( u) ;
int flag= 0 ;
while ( ! q. empty ( ) ) {
u= q. front ( ) ; q. pop ( ) ;
if ( u. x== enx&& u. y== eny) {
printf ( "%d\n" , u. step) ;
flag= 1 ;
break ;
}
for ( int i= 0 ; i< 4 ; i++ ) {
v. x= u. x+ f[ i] [ 0 ] ;
v. y= u. y+ f[ i] [ 1 ] ;
if ( check ( v. x, v. y) && mp[ v. x] [ v. y] == 1 && vis[ v. x] [ v. y] == 0 ) {
vis[ v. x] [ v. y] = 1 ;
v. step= u. step+ 1 ;
q. push ( v) ;
}
}
}
if ( flag== 0 )
printf ( "-1\n" ) ;
return ;
}
int main ( )
{
scanf ( "%d%d" , & n, & m) ;
for ( int i= 1 ; i<= n; i++ ) {
for ( int j= 1 ; j<= m; j++ ) {
scanf ( "%d" , & mp[ i] [ j] ) ;
}
}
scanf ( "%d%d%d%d" , & stx, & sty, & enx, & eny) ;
bfs ( ) ;
return 0 ;
}
并查集
# include <bits/stdc++.h>
using namespace std;
const int maxn= 1e6 + 10 ;
int f[ maxn] ;
int n, m;
void init ( ) {
for ( int i= 1 ; i<= n; i++ ) f[ i] = i;
}
int find ( int x) {
if ( x== f[ x] ) return x;
return f[ x] = find ( f[ x] ) ;
}
void merge ( int x, int y) {
int tx= find ( x) ;
int ty= find ( y) ;
if ( tx!= ty) {
f[ ty] = tx;
}
}
int main ( )
{
cin>> n>> m;
init ( ) ;
for ( int i= 1 ; i<= m; i++ ) {
int id;
int x, y;
scanf ( "%d" , & id) ;
if ( id== 1 ) {
scanf ( "%d%d" , & x, & y) ;
merge ( x, y) ;
}
else {
scanf ( "%d%d" , & x, & y) ;
if ( find ( x) == find ( y) ) {
cout<< "YES" << endl;
}
else {
cout<< "NO" << endl;
}
}
}
return 0 ;
}
快速幂
LL mypow ( LL n, LL k, LL mod)
{
LL res= 1 ;
while ( k) {
if ( k& 1 ) {
res= ( res* n) % mod;
}
k>>= 1 ;
n= ( n* n) % mod;
}
return res;
}