529 扫雷游戏

该题可以采用深度优先搜索或者广度优先搜索,深度优先搜索更适合。·

class Solution {    
int[] dx = {-1, -1, 0, 1, 1, 1, 0, -1}; // 相邻位置
int[] dy = {0, 1, 1, 1, 0, -1, -1, -1};
    public char[][] updateBoard(char[][] board, int[] click) {        
    		dfs(board, click[0], click[1]);
   		eturn board;    }
    public void dfs(char[][] board, int x, int y) {
            int r = board.length;        
            int c = board[0].length;        
            if (x < 0 || x >= r || y < 0 || y >= c) {            return;        }
        if (board[x][y] == 'E') { // 如果当前为E,才进行判断是否要递归相邻结点           
	         board[x][y] = 'B';    
	        int count = judge(board, x, y);            
	        if (count == 0) { // 如果为0,则进行递归         
	               for (int i = 0; i < 8; i++) {             
	                      dfs(board, x + dx[i], y + dy[i]);                }            } else { // 如果不为0,则更新当前结点的值为地雷数量                
	                      board[x][y] = (char) (count + '0');   
         }     
   } else if (board[x][y] == 'M'){ // 注意不要用else,否则会递归修改掉已经是数字的位置        
       board[x][y] = 'X';    
       }  
  }
    // 获取当前借点相邻的地雷数量   
 public int judge(char[][] board, int x, int y) {    
     int r = board.length;     
        int c = board[0].length;   
             int count = 0;   
                  for (int i = 0; i < 8; i++) {          
                    int newX = x + dx[i];            
                    int newY = y + dy[i];           
                     if (newX < 0 || newX >= r || newY < 0 || newY >= c) {                continue;            }           
                      if (board[newX][newY] == 'M') {                count++;            
                      }      
                        }        
return count;   
 }
    static class Node {        int x;        int y;        Node(int x, int y) {            
    this.x = x;            this.y = y;    
        }   
 }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值