【Lintcode】1892. Mine-sweeping

题目地址:

https://www.lintcode.com/problem/mine-sweeping/description

给定一个 m m m n n n列的二维矩阵 A A A 1 1 1代表空地, 0 0 0代表地雷。给定一个出发点,每步可以四个方向走一格。如果走到地雷上,就不能继续走了,否则的话还可以继续走。问能走到的所有格子的坐标。出发点可以是地雷,那答案就是出发点自己。

思路是BFS。代码如下:

import java.util.*;

public class Solution {
    /**
     * @param Mine_map: an array represents the map.
     * @param Start:    the start position.
     * @return: return an array including all reachable positions.
     */
    public List<List<Integer>> Mine_sweeping(int[][] Mine_map, int[] Start) {
        // write your code here
        List<List<Integer>> res = new ArrayList<>();
        
        int x = Start[0], y = Start[1];
        if (Mine_map[x][y] == 0) {
            res.add(Arrays.asList(x, y));
            return res;
        }
        
        int m = Mine_map.length, n = Mine_map[0].length;
        
        Queue<int[]> queue = new LinkedList<>();
        boolean[][] visited = new boolean[m][n];
        visited[x][y] = true;
        queue.offer(Start);
        
        // 别忘了将起点加入答案里
        res.add(Arrays.asList(x, y));
        
        int[] d = {1, 0, -1, 0, 1};
        while (!queue.isEmpty()) {
            int[] cur = queue.poll();
            for (int i = 0; i < 4; i++) {
                int nextX = cur[0] + d[i], nextY = cur[1] + d[i + 1];
                if (0 <= nextX && nextX < m && 0 <= nextY && nextY < n && !visited[nextX][nextY]) {
                	// 标记一下访问过
                    visited[nextX][nextY] = true;
                    // 走到的地方加入答案
                    res.add(Arrays.asList(nextX, nextY));
                    // 只有空地才能继续拓展
                    if (Mine_map[nextX][nextY] == 1) {
                        queue.offer(new int[]{nextX, nextY});
                    }
                }
            }
        }
        
        return res;
    }
}

时空复杂度 O ( m n ) O(mn) O(mn)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值