前言
###我做这类文章一个重要的目的还是给正在学习的大家提供方向和记录学习过程(例如想要掌握基础用法,该刷哪些题?)我的解析也不会做的非常详细,只会提供思路和一些关键点,力扣上的大佬们的题解质量是非常非常高滴!!!
习题
1.扫雷游戏
题目链接: 529. 扫雷游戏 - 力扣(LeetCode)分析:注意只有相邻没有地雷的方块被挖后继续递归下去
代码:
java
class Solution {
char[][] board;
int[][] flag;
int n, m;
public char[][] updateBoard(char[][] board, int[] click) {
this.board = board;
n = board.length;
m = board[0].length;
flag = new int[n][m];
if (board[click[0]][click[1]] == 'M') {
board[click[0]][click[1]] = 'X';
return board;
}
recursion(click[0], click[1]);
return board;
}
public void recursion(int x,int y){
flag[x][y] = 1;
char c = line(x,y);
// System.out.println(x+" "+y+" "+c);
if(c=='0'){
board[x][y] = 'B';
if(x+1<n){
if(board[x+1][y]=='E'&&flag[x+1][y]==0){
recursion(x+1,y);
}
if(y+1<m&&board[x+1][y+1]=='E'&&flag[x+1][y+1]==0){
recursion(x+1,y+1);
}
if(y-1>=0&&board[x+1][y-1]=='E'&&flag[x+1][y-1]==0){
recursion(x+1,y-1);
}
}
if(x-1>=0){
if(board[x-1][y]=='E'&&flag[x-1][y]==0){
recursion(x-1,y);
}
if(y+1<m&&board[x-1][y+1]=='E'&&flag[x-1][y+1]==0){
recursion(x-1,y+1);
}
if(y-1>=0&&board[x-1][y-1]=='E'&&flag[x-1][y-1]==0){
recursion(x-1,y-1);
}
}
if(y-1>=0&&board[x][y-1]=='E'&&flag[x][y-1]==0){
recursion(x,y-1);
}
if(y+1<m&&board[x][y+1]=='E'&&flag[x][y+1]==0){
recursion(x,y+1);
}
}else{
board[x][y] = c;
}
}
public char line(int x,int y){
int flag = 0;
if(x+1<n){
if(board[x+1][y]=='M')flag++;
if(y+1<m&&board[x+1][y+1]=='M')flag++;
if(y-1>=0&&board[x+1][y-1]=='M')flag++;
}
if(x-1>=0){
if(board[x-1][y]=='M')flag++;
if(y+1<m&&board[x-1][y+1]=='M')flag++;
if(y-1>=0&&board[x-1][y-1]=='M')flag++;
}
if(y-1>=0&&board[x][y-1]=='M'){
flag++;
}
if(y+1<m&&board[x][y+1]=='M'){
flag++;
}
return (char)('0'+flag);
}
}
2.二维网格图中探测环
题目链接: 1559. 二维网格图中探测环 - 力扣(LeetCode)
附上大佬代码:
java
class Solution {
public boolean containsCycle(char[][] grid) {
m = grid.length;
n = grid[0].length;
visited = new boolean[m][n];
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j)
if (!visited[i][j] && bfs(i, j, grid))
return true;
return false;
}
private boolean bfs(int i, int j, char[][] grid) {
queue.offer(new int[]{i, j});
visited[i][j] = true;
while (!queue.isEmpty()) {
int[] node = queue.poll();
int neibors = 0, size = queue.size();
for (int[] dir : dirs) {
int row = node[0] + dir[0], col = node[1] + dir[1];
if (isValid(row, col) && grid[row][col] == grid[node[0]][node[1]]) {
++neibors;
if (!visited[row][col]) {
queue.offer(new int[]{row, col});
visited[row][col] = true;
}
}
}
if (neibors - 1 > queue.size() - size)
return true;
}
return false;
}
int m, n;
boolean[][] visited;
Queue<int[]> queue = new LinkedList<>();
int[][] dirs = new int[][]{{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
private boolean isValid(int i, int j) {
return i >=0 && j >= 0 && i < m && j < n;
}
}
后言
上面是力扣图论专题,下一篇是其他的习题,希望有所帮助,一同进步,共勉!