1559. 二维网格图中探测环(leetcode)
class Solution {
int[] dx={0,1,0,-1};
int[] dy={1,0,-1,0};
int n;
int m;
char[][] grid;
boolean[][] vis;
int startx;
int starty;
boolean canRing;
public boolean containsCycle(char[][] grid) {
// 能否连成环 关键是 移动后能回到起始点位置
m=grid.length;
n=grid[0].length;
vis=new boolean[m][n];
this.grid=grid;
for(int i=0;i<m;i++)
for(int j=0;j<n;j++)
{
if(vis[i][j]==true)continue;
dfs(i,j,new int[]{-1,-1}); // 上一步不存在
if(canRing) return canRing;
}
return canRing;
}
void dfs(int x,int y,int[] lastPoint)
{
if(vis[x][y]==true){
canRing = true;
return;
}
vis[x][y]=true;
for(int i=0;i<4;i++)
{
int a=dx[i]+x,b=dy[i]+y;
if(a==lastPoint[0] && b==lastPoint[1])continue;
if(a>=0 && b>=0 && a<m && b<n && grid[a][b]==grid[x][y])
{
dfs(a,b,new int[]{x,y});
}
}
}
}