-
Lesson 1 - 最简单的C程序
-
Lesson 2 - 打印输出
-
Lesson 3 - 循环打印
-
Lesson 4 - 判断奇偶
-
Lesson 5 - 从1加到100求和
-
Lesson 6 - 乘法表
-
Lesson 7 - 求100以内的最大素数
-
Lesson 8 - 1到100有多少个9
-
Lesson 9 - 整型转字符串
-
Lesson 10 - 约瑟夫环
-
Lesson 11 - 求两个坐标点之间的距离
-
Lesson 12 - 判断机器存储是否小尾端
-
Lesson 13 - 对不起,你的车今天限行
-
Lesson 14 - 判断地图上某点是否有出路
-
Lesson 15 - 统计一个数二进制表示中1的个数
-
Lesson 16 - 字符串拷贝
-
Lesson 17 - 统计单词个数
-
Lesson 18 - 实现 printf
-
Lesson 19 - 命令解释器
-
Lesson 20 - 预处理器实现
-
Lesson 21 - 词法分析器实现
-
Lesson 22 - 猜数游戏
-
Lesson 23 - 五子棋
-
Lesson 24 - 超链接分析器
-
Lesson 25 - cp命令实现
-
Lesson 26 - ELF文件头分析器实现
-
Lesson 27 - 简单流处理器实现和正则表达式
-
Lesson 28 - 数学计算器实现
-
Lesson 29 - 数学计算器实现more命令实现
-
Lesson 30 - sort命令实现
-
Lesson 31 - ls -l命令实现
-
Lesson 32 - Bash项目
-
Lesson 33 - 动态数组实现
-
Lesson 34 - 约瑟夫环问题
-
Lesson 35 - 表达式求值问题
-
Lesson 36 - 广度优先解决迷宫问题
-
Lesson 37 - 词频统计器
-
Lesson 38 - 堆排序问题
-
Lesson 39 - 构造符号表
-
Lesson 40 - MyDictionary项目
-
Lesson 41 - BSearch 实现
-
Lesson 42 - QSort 实现
-
Lesson 43 - 深度优先解决迷宫问题
-
Lesson 44 - KMP 算法实现
-
Lesson 45 - 最长公共子序列(LCS)问题
-
Lesson 46 - Dijkstra 算法
-
Lesson 47 - Huffman Coding 算法
-
Lesson 48 - 地图导航项目
Lesson 14 Is there a way out? 判断地图上某点是否有出路
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
/* define chessboard size */
#define ROW 10
#define COL 10
/* define chessboard using matrix */
int chessboard[ROW][COL] = { {0} };
void init(int board[ROW][COL])
{
int i, j;
srand(time(NULL));
for (i = 0; i < ROW; i++)
for (j = 0; j < COL; j++)
board[i][j] = rand() % 2;
return;
}
/* display chessboard using printf */
void print(int board[ROW][COL])
{
int i, j;
printf("\n");
printf(" ");
for (j = 0; j < COL; j++)
printf(" %d", j);
printf("\n");
printf(" -");
for (j = 0; j < COL; j++)
printf(" -");
printf("\n");
for (i = 0; i < ROW; i++) {
printf("%d| ", i);
for (j = 0; j < COL; j++) {
printf("%d ", board[i][j]);
}
printf("\n");
}
printf("\n");
}
/* test (x, y) is valid before put chess */
int onboard(int x, int y)
{
if (x >= ROW || x < 0)
return 0;
if (y >= COL || y < 0)
return 0;
return 1;
}
int check(int x, int y)
{
int i = 0;
int counter = 1;
int nx, ny; // next x y
// up, down, left, right,
int dirx[4] = { -1, 1, 0, 0 };
int diry[4] = { 0, 0, -1, 1 };
counter = 0;
// 4 directions
for (i = 0; i < 4; i++)
{
nx = x;
ny = y;
nx += dirx[i];
ny += diry[i];
// if (nx, ny) is out of board, then continue;
if (!onboard(nx, ny))
continue;
if (chessboard[nx][ny] == 0)
{
counter++;
printf("there is %d direction (%d, %d) out!\n", counter, dirx[i], diry[i]);
}
}
return counter;
}
int main(int argc, char *argv[])
{
int x = 4, y = 4;
int ways = 0;
print(chessboard);
init(chessboard);
print(chessboard);
printf("please input a point position: ");
scanf("%d %d", &x, &y);
printf("point(%d, %d)\n", x, y);
ways = check(x, y);
printf("Total is %d way out!\n", ways);
return 0;
}
copy
知识点
- 二维数组 a[][]
- 随机函数 rand()
课堂讨论
- dirx 和 diry 的数组在代码易读性上是否还有改进的空间?
- 如果在方向判断上,要加上左上,左下,右上,右下这4个方向,如何修改?
课后练习
- 请打印杨辉三角形的前10行。打印输出格式可以参考 http://baike.baidu.com/view/298289.htm