LeetCode探索(深度优先遍历和广度优先遍历)

扫雷游戏

题目:https://leetcode-cn.com/problems/minesweeper/
题目大意:
就是扫雷游戏,实在是太长了,还是自己看吧。

分析:
题目比较长,读懂题目意思之后思路不难。
这道题目个人感觉用BFS会简单一些,结果自己写的超时了。看了一下官方解法,感觉这种走格子的题目还是有很多小技巧的。

如何遍历周围的格子

之前我每次使用BFS或者DFS的时候,都是写4个if,但是像这道题要写8个if,如果每次能走两圈那不是要写15if?太多了,而且很容易出错,这里可以使用两个数组把需要遍历点的偏移记录下来,然后使用for循环逐个遍历,遇到超出边界的就直接丢弃。

int[] dx = new int[]{-1,-1,-1,0,0,1,1,1};
int[] dy = new int[]{-1,0,1,-1,1,-1,0,1};
for(int i=0;i<8;i++){
	int tx = x+dx[i];
	int ty = y+dy[i];
    if(tx<0 || tx >= m || ty<0 || ty >= n)
       continue;
    ....//具体逻辑	
}

如何计算对角线

这个不是扫雷这道题的,而是N皇后和数独的技巧。
对于从左上到右下的对角线来说满足以下特性:
i=j+m
m是偏移量,如果是4*4的棋盘,那么m>-4 && m <4
对于从左下到右上的对角线来说,满足以下特性:
i+j=n
公式也非常简单,想一想最小的对角线元素为(0,0),最大的是(3,3),所以有n>=0 && n < 2*(4-1)

去重

BFS不同于DFS,是先将节点加入队列中之后再遍历的,所以在加入的时候就有可能重复,这些重复的点会带来大量的额外时间复杂度导致超时。
所以一般BFS在将一个点加入队列之后就把这个点标记为已访问。

queue.offer(new int[]{tx,ty});
visited[tx][ty] = true;

扫雷游戏的代码

class Solution {
    public char[][] updateBoard(char[][] board, int[] click) {
        if(board[click[0]][click[1]] == 'M'){
            board[click[0]][click[1]] = 'X';
            return board;
        }
        int m = board.length;
        int n = board[0].length;
        int[] dx = new int[]{-1,-1,-1,0,0,1,1,1};
        int[] dy = new int[]{-1,0,1,-1,1,-1,0,1};
        boolean[][] visited = new boolean[m][n];
        Queue<int[]> queue = new LinkedList<>();
        queue.add(click);
        while(!queue.isEmpty()){
            int[] pos = queue.poll();
            int x = pos[0];
            int y = pos[1];
            visited[x][y] = true;
            int count = 0;
            for(int i=0;i<8;i++){
                int tx = x+dx[i];
                int ty = y+dy[i];
                if(tx<0 || tx >= m || ty<0 || ty >= n)
                    continue;
                if(board[tx][ty] == 'M')
                    count++;
            }
            if(count == 0){
                board[x][y] = 'B';
                for(int i=0;i<8;i++){
                int tx = x+dx[i];
                int ty = y+dy[i];
                if(tx<0 || tx >= m || ty<0 || ty >= n || board[tx][ty] != 'E' || visited[tx][ty])
                    continue;
                queue.offer(new int[]{tx,ty});
                visited[tx][ty] = true;
                }
            }else{
                board[x][y] = (char)('0'+count);
            }
        }
        return board;
    }
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值