• 五子棋-牛客网


    NowCoder最近爱上了五子棋,现在给你一个棋局,请你帮忙判断其中有没有五子连珠(超过五颗也算)。
    
    输入描述:
    输入有多组数据,每组数据为一张20x20的棋盘。
    
    其中黑子用“*”表示,白子用“+”表示,空白位置用“.”表示。
    
    
    输出描述:
    如果棋盘上存在五子连珠(无论哪种颜色的棋子),输入“Yes”,否则输出“No”。
    1. // write your code here
    2. import java.util.*;
    3. public class Main{
    4. final static int N=20;
    5. public static void main(String[] args){
    6. Scanner sc =new Scanner(System.in);
    7. while(sc.hasNext()){
    8. char[][] map = new char[N][N];
    9. for(int i = 0; i < N; ++i){
    10. map[i] = sc.next().toCharArray();
    11. }
    12. System.out.println(solve(map)? "Yes" : "No");
    13. }
    14. }
    15. // 遍历map的每一个位置
    16. public static boolean solve(char[][] map){
    17. for(int i = 0; i < N; ++i){
    18. for(int j = 0; j < N; ++j){
    19. // 如果该位置有符号,则进行搜索
    20. if('+' == map[i][j] || '*' == map[i][j]){
    21. if(isWin(map, map[i][j], i, j) >= 5)
    22. return true;
    23. }
    24. }
    25. }
    26. return false;
    27. }
    28. public static int isWin(char[][] map,char ch,int x,int y){
    29. int[][][] pos={
    30. {{-1, 0}, {1, 0,}},
    31. {{0, -1,}, {0, 1}},
    32. {{-1, -1}, {1, 1}}
    33. , {{-1, 1}, {1, -1}}};
    34. int maxcount=0;
    35. //八个方向搜索
    36. for(int i=0;i<4;i++){
    37. int count=0;
    38. for(int j=0;j<2;j++){
    39. int nx = x;
    40. int ny = y;
    41. while(nx >= 0 && nx < N && ny >= 0 &&
    42. ny< N && map[nx][ny] ==ch){
    43. count++;
    44. nx+=pos[i][j][0];
    45. ny+=pos[i][j][1];
    46. }
    47. }
    48. maxcount=Math.max(maxcount,count);
    49. }
    50. return maxcount-1;
    51. }
    52. }

    【解题思路】
    结构设计:dir代表当前位置的8个方向,其中上下、左右、左上右下、右上左下为必须放在一起
    检测。
    获取一个棋盘,按照行列检测棋盘中的每个位置,当拿到一个位置后,按照以下步骤进行操作:
    1. 以该位置为中心,依次检测该位置的上下、左右、左上右下、右上左下,比如左上
    2. 从该位置开始向上检测,找出连在一起的同种棋子个数,再向下检测同种棋子的个数并累
    计,注意在检测时,中心位置统计了两次,上下统计完时,需要给结果减去1
    3. 按照2统计完上下、左右、左上右下、右上左下各个方向,找出最大的同种棋子个数
    4. 检测3中统计出的最大同种棋子个数,如果大于等于5,输出YSE,否则取下一个位置继续1
    5. 如果所有的位置检测完,没有超过5个的相同棋子,则输出NO
     

  • 相关阅读:
    在X11图形环境下开启/关闭勿扰模式及其背后机制
    精准测试探索
    整理正则表达式(最全包括js表单验证)
    Xcode 15 运行<iOS 14, 启动崩溃问题
    云原生之旅 - 7)部署Terrform基础设施代码的自动化利器 Atlantis
    计算机网络--HTTP 协议的请求方式 GET 和 POST
    Python 基础学习
    K8s(Kubernetes)学习(四):Controller 控制器:Deployment、StatefulSet、Daemonset、Job
    Apollo学习笔记(27)李群、李代数
    一个工作薄中快速新建多个数据表
  • 原文地址:https://blog.csdn.net/qq_60991267/article/details/126618630