• 五子棋-牛客网


    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
     

  • 相关阅读:
    腾讯云死磕政务云?
    Echarts-实现3D柱状图
    JWT身份验证
    springboot新冠疫苗预约系统在线视频点播系统毕业设计毕设作品开题报告开题答辩PPT
    SMART PLC累计流量功能块(梯形积分法+浮点数累加精度控制)
    Day19—Scrapy框架高级特性
    OpenHarmony藏头诗应用
    NCV7705DQAR2G 汽车电机驱动器(NCV7705DQR2G)引脚配置
    【软件测试】作为测试人,因工作与开发吵了一架碰撞,该咋办......
    MybatisPlus【SpringBoot】 6 插件 6.1 分页插件 & 6.2 xml 自定义分页
  • 原文地址:https://blog.csdn.net/qq_60991267/article/details/126618630